How to check whether object Containing object collection - java

In Java i want to find whether object is a object collection??
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
I want to check varaible ob holds object collection??How can i do this??

You can use Java reflections, like this:
Class<?> clazz = ob.getClass();
boolean isArray = clazz.isArray();

check with instanceof operator.
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that >implements a particular interface.
reference
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
...
if(ob instanceof String[]){
String[] str = (String[])ob;
}else{...}

From your example, what you need to check is more precisely, Object Array instead of collection.
You can try something like
String [] abc=new String[]{"Joe","John"};
Object ob=abc;
if (ob instanceof Object[]) {
// do something
}

First check is it an array with:
boolean isArray = ob.getClass().isArray();
or
if (ob instanceof Object[]) {
// ...
}
If not check is it an collection by checking with instanceof and java.util.Collection interface:
if (ob instanceof Collection) {
// ...
}

Related

Call Overloaded methods with ternary operator?

What is the rule that I can not call overloaded methods with checking instanceOf with ternary operator?
It may be a stupid question, but I want little explanation about this rule. You can see in screenshot, I can not refer to multiple methods by using the ternary operator.
public class Sample {
public static void main(String[] args) {
Object object = new String("");
Foo.load(object instanceof Integer ? (Integer) object :
object instanceof String ? (String) object : null);
}
public static class Foo {
public static void load(String s) {
//
}
public static void load(Integer s) {
//
}
}
}
Method resolution is done in compile time. At the end of the day, you pass some expression that returns a value to a method. The compiler inspects the expression's type and determines which method it should call.
Here, you're attempting to write an expression that may return different types according to runtime information and invoke a method accordingly. And as you've seen, this just won't fly. Instead, you could explicitly invoke the different methods according to the type (the fact that they have the same name is inconsequential - they are still different methods!):
if (object instanceof Integer) {
Foo.load((Integer) object); // Calls Foo.load(Integer)
} else if (object instanceof String) {
Foo.load((String) object); // Calls Foo.load(String)
} else {
Foor.load(object); // Calls Foo.load(Object)
}
Object obj = getObject();
if(obj instanceof Integer)
load((Integer)obj);
else if(obj instanceof String)
load((String)obj);
else
load(obj);
Error, because the overloaded method is been choosen at the compilation time, but not runtime, when you use instanceof. To move this check to the runtime, do use e.g. if...else.
HINT
load(obj instanceof String ? (String)obj : obj);
This is OK and does not throw compilation error, but what do you think, which overloaded method will be called, when obj = "some string", load(String s) ???
NO!!! load(Object s) for both String and Object instance.
In your case, an empty string or null doesnot test for reference equality.
Your solution will work if the Object object = new String("test");
is there.
Also, for primitive types like int, float etc you don't really need instanceof.. instanceof is more for classes.
Here is a link on how instanceof really works:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

Comparison of Java objects [duplicate]

This question already has answers here:
Parentheses around data type?
(5 answers)
Closed 7 years ago.
I'm new to Java, and am reading a Java book; at one point it talks about when you may want to override the built in function, equals(). For instance, if an object has a variable ID, and two objects have the same ID, you may want them to be considered to be equal. It gave example code which looks more or less like:
public boolean equals(Object obj) {
if((obj != null) && (obj instanceof myClass)) {
myClass object1 = (myClass)obj;
if(this.ID == object1.ID) {
return true;
}
}
return false;
}
I don't fully understand what's going on in the third line. I'm unsure about why it's necessary and you can't just compare obj.ID and this.ID in the if() statement. My guess is that it's because obj is just declared as a generic object which may not have an ID, so you need to create a new object, object1 which is of the correct class to look at the ID.
Am I correct here? What exactly is going on in that line?
In your code Object obj is a reference to an Object. The code at this point makes no assumptions about which type of Object it is.
When you do
myClass object1 = (myClass) obj;
you are casting the type of the reference to an object which this will either succeed because it is an instance of that type or fail throwing ClassCastException.
This creates a new reference but the underlying object is unchanged by this, nor is it copied.
Note: the obj != null check is redundant as null is not an instanceof of any class, nor does it trigger an exception. i.e.
Object o = null;
boolean b = o instanceof Object; // always false, never throws an exception.
A shorter version of this method could read.
public boolean equals(Object obj) {
if(obj instanceof myClass) {
myClass object1 = (myClass)obj;
return ID == object1.ID;
}
return false;
}
or even
public boolean equals(Object obj) {
return obj instanceof myClass && ID == ((myClass) obj).ID;
}
In Java 8 you could write
public boolean equals(Object obj) {
return Optional.ofNullable(obj)
.filter(o - > o instanceof myClass)
.map(o -> (myClass) o)
.filter(m -> ID == m.ID)
.isPresent();
}
On the 3rd line, no object is being created.
The first thing you need to understand about java is that there are primitives like int, char, double and objects, which are everything else, and objects are always accessed by reference.
So, Object obj is a reference to objects of type Object, and at runtime it will be referring to some object.
Then, further down, when you say myClass object1 you are not creating any object; you are just declaring a variable called object1 which will be referring to objects of type myClass. But there is no object yet.
So, when you say myClass object1 = (myClass)obj; you are assigning the reference obj to the reference object1. And since it would normally be invalid to make an assignment between different types, you are using a type cast (the (myClass) part) to tell the compiler that you know what you are doing, and you are sure that obj will be pointing to an object of type myClass at that point. So, the compiler allows you to make the assignment.
After the assignment, both obj and object1 are pointing to the same object, but the usefulness of object1 now is that you can view this object as an object of type myClass, so you can access its members.
Your guess is almost correct: obj is declared to have type Object and Object can be anything, a String for example, it does not have to have the member named ID, so, you can't just look at it to compare. So, the code you quoted first check if the obj is of the same type (if it isn't, then you know it does not equal), and then (on the line you are asking about) casts it to that type.
I said, your guess was almost correct, because you suggested that a new object of type myClass is created. This is not true. The assignment myClass object1 = (myClass)obj; does not create any new objects, it merely makes a new variable object1 refer to to the same object referred by obj, and tells the compiler that it should now know that that object is actually of type myClass.
Yes. The third line is inside an if statement that says obj instanceof myClass. At that point you know that it is of type myClass. Assuming myClass has an ID like in your code then you know that both objects have ID properties and you can use those for comparison.
Research the term "Object Casting".
the obj instanceof myClass is making sure that obj is the same type as this. Now we know it is safe to cast and Object obj into a myClass object1
The test for null is not needed, because instanceof is false for nulls.
Just use:
if (obj instanceof myClass) {
Otherwise, your code is fine, assuming ID is a primitive (especially, not a String).

How can I return objects of different type from a single function?

I need to return objects of different classes in a single method using the keyword Object as the return type
public class ObjectFactory {
public static Object assignObject(String type) {
if(type.equalsIgnoreCase("abc")){
return new abcClass();
} else if(type.equalsIgnoreCase("def")) {
return new defClass();
} else if(type.equalsIgnoreCase("ghi")) {
return new ghiClass();
}
return null;
}
}
and in another class I am trying to get the objects as
public class xyz{
public void get(){
Object obj=(abcClass)ObjectFactory.assignObject("abc");
}
}
How can I access the methods in abcClass using the obj object??
Your current code will throw an exception if assignObject returns an instance that is not an abcClass, so you can change the type of obj to absClass :
public void get(){
abcClass obj=(abcClass)ObjectFactory.assignObject("abc");
}
I would suggest as one of the commentators on your initial post did. That is, refactor this to use an interface.
Your classes AbcClass, DefClass, and GhiClass, could all implement an interface, lets call it Letters. You can then define a class called LettersFactory, with the method createLetters. At this point, I'd also recommend changing your hard coded string identifiers into an enumeration. For instance:
public enum LetterTypes { ABC, DEF, GHI }
You're factory method can then accept this enumeration, and you have no fears of getting invalid values. The factory method can also return the type Letters (the interface) and you have a more specific version of Object (which is good).
Finally, if you need to determine these types on the fly, you can have a method defined in Letters (forcing all children to implement it) called getType() which returns the LetterTypes enumeration for the class that is implemented.
You could also use the instanceof operator to determine which class you have.
Cheers,
Frank
You can use this as a refrence :-
public Object varyingReturnType(String testString ){
if(testString == null)
return 1;
else return testString ;
}
Object o1 = varyingReturnType("Lets Check String");
if( o1 instanceof String) //return true
String now = (String) o1;
Object o2 = varyingReturnType(null);
if( o2 instanceof Integer) //return true
int i = (Integer)o2;
So similarly you can use your own conditions along with the instanceof operator and can cast it to get the actual object type from Object type.

Checking if an object is an instance of a specific datatype given by a user

I am struggling with checking if an object is an instance of a specific datatype, which is given by user input. For example:
Object a = new Object();
String userDataType = JOptionPane.showInputDialog("What kind of datatype do you want to check?");
if(Object a instanceof userDataType)) doStuff();
I tried reflections but I still don't manage to get behind this...
Thank you in advance!
Try comparing with the getSimpleName() of the class of the object, which returns just the unqualified class name (without the package name).
Object o;
String userInput;
if (o.getClass().getSimpleName().equalsIgnoreCase(userInput))
The instanceof keyword works by comparing it to an actual object type, not a string. For example:
Object a = getUseObject();
if( a instanceof String ) doStuff(); // if a is actually a String
else if (a instanceof double[]) doStuff(); // if a is actually an array of doubles
Cast it to the datatypes you wish to check for, handle exceptions as required.

How do I check if a given object is an instance of certain class when in Object[] array?

I was trying to find out how to determine which class a given object instantiate when it's in Object[] array. For example:
Object[] array = new Object[]{175, "sss", new Table(), true};
Object obj = array[0]; // hmm... can this be used as an integer or maybe as a string?
Is it even possible?
You can call getClass() to find out the class of a particular object, or you can use instanceof to check a specific type:
if (array[0] instanceof Integer) {
}
Normally having to do a lot of this indicates a weakness in your design though - you should try to avoid needing to do this.
You can try using instanceof or you can try getClass().isAssignableFrom(), whatever fits your needs
You can test whether it is an instance of a pre-known class (and cast it) like this:
if (obj instanceof String) {
String s = (String) obj; //casts the obj now you know it's a String
}
I like to think of this not as making any changes to the object but just as revealing its true character. For example, it's a bit like seeing a person and not knowing what language they speak - the person is still French, or Italian, just that you don't know which yet. The cast (i.e. (String) obj) is you telling the compiler the equivalent of "I know this person speaks French"
Or you can gets its class like this:
Class<?> clazz = obj.getClass();
A Class instance can be used to make the same check:
String.class.isInstance(obj) {
String s = String.class.cast(obj);
}

Categories