if (obj instanceof C) {
//your code
}
Answer from IAdapter on Stack Overflowif (obj instanceof C) {
//your code
}
Use Object.getClass. It returns the runtime type of the object. Here's how to call it using your example:
class A {}
class B extends A {}
class C extends A {}
class Main {
public static void main(String args[]) {
C c = new C();
Class clazz = c.getClass();
System.out.println(clazz);
}
}
Output:
class C
You can also compare two Class instances to see if two objects are the same type.
class A {}
class B extends A {}
class C extends A {}
class Main {
public static void main(String args[]) {
B b = new B();
Class c1 = b.getClass();
C c = new C();
Class c2 = c.getClass();
System.out.println(c1 == c2);
}
}
How do i check if an object is an instance of a class while having the name of that class passed as a parameter?
How to Get Type's Class of a Collection - Oracle Forums
[Java] How do I get the name of the class that called my object's constructor?
How can I get the generic type of a List from a Class instance?
Essentially i want to count the number of instances in an array that are of a certain type. My idea was to have a countInstances method, which takes as a parameter a string called type, and increments the counter if an item in the array is an instance of type. However, this doesn’t work because java seems to check literally whether the item in the array is of class type (whixh doesn’t exist) rather than checking if it is an instance of whatever the content of the type string is…
I have class A with a String origin field and a getter for said field. I want A's constructor to do the following:
- Check whether the method where A got initialized (i.e. the method that called A's constructor) is static or not
- If it's static, initialize the origin field with the name of the class said method belongs to. If the method has been overridden down the hierarchy, I want the name of the class used to CALL the method, rather than the one that implemented it or the interface that declared it.
- If it's NOT static, initialize the origin field with the name of the whatever instance was used to call said method.
Is it possible to do something like this, and if so: how?