If class B
and class C
extend class A
and I have an object of type B
or C
, how can I determine of which type
I use the blow function in my GeneralUtils class, check it may be useful
public String getFieldType(Object o) {
if (o == null) {
return "Unable to identify the class name";
}
return o.getClass().getName();
}
Use Object.getClass(). It returns the runtime type of the object.
if (obj instanceof C) {
//your code
}
You can use getSimpleName().
Let's say we have a object: Dog d = new Dog(),
The we can use below statement to get the class name: Dog. E.g.:
d.getClass().getSimpleName(); // return String 'Dog'.
PS: d.getClass() will give you the full name of your object.
There is also an .isInstance method on the "Class
" class. if you get an object's class via myBanana.getClass()
you can see if your object myApple
is an instance of the same class as myBanana
via
myBanana.getClass().isInstance(myApple)
I Used Java 8 generics to get what is the object instance at runtime rather than having to use switch case
public <T> void print(T data) {
System.out.println(data.getClass().getName()+" => The data is " + data);
}
pass any type of data and the method will print the type of data you passed while calling it. eg
String str = "Hello World";
int number = 10;
double decimal = 10.0;
float f = 10F;
long l = 10L;
List list = new ArrayList();
print(str);
print(number);
print(decimal);
print(f);
print(l);
print(list);
Following is the output
java.lang.String => The data is Hello World
java.lang.Integer => The data is 10
java.lang.Double => The data is 10.0
java.lang.Float => The data is 10.0
java.lang.Long => The data is 10
java.util.ArrayList => The data is []