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 it is an instance?
- 14@starblue Casting would be the first thing that comes to mind. I doubt the instanceof operator would exist if there wasn't any need for it.arkon– arkon2012-09-14 07:16:40 +00:00Commented Sep 14, 2012 at 7:16
- @b1nary.atr0phy wouldn't it be good to use the isntanceof operator first. If there's a cast to an incompatible type, I believe that will result in a ClassCastExceptioncommittedandroider– committedandroider2019-10-12 17:27:11 +00:00Commented Oct 12, 2019 at 17:27
14 Answers
if (obj instanceof C) { //your code } 7 Comments
if(!(obj instanceof C))code Child1 child1 = new Child1(); Parent1 parentChild = new Child2(); Child2 child2 = new Child2(); (child1 instanceof Parent1); (child1 instanceof Child1); (parentChild instanceof Child2); (parentChild instanceof Parent1); (parentChild instanceof Child1); code , it may clear the intent of instanceof.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); } } 4 Comments
Multiple right answers were presented, but there are still more methods: Class.isAssignableFrom() and simply attempting to cast the object (which might throw a ClassCastException).
Possible ways summarized
Let's summarize the possible ways to test if an object obj is an instance of type C:
// Method #1 if (obj instanceof C) ; // Method #2 if (C.class.isInstance(obj)) ; // Method #3 if (C.class.isAssignableFrom(obj.getClass())) ; // Method #4 try { C c = (C) obj; // No exception: obj is of type C or IT MIGHT BE NULL! } catch (ClassCastException e) { } // Method #5 try { C c = C.class.cast(obj); // No exception: obj is of type C or IT MIGHT BE NULL! } catch (ClassCastException e) { } Differences in null handling
There is a difference in null handling though:
- In the first 2 methods expressions evaluate to
falseifobjisnull(nullis not instance of anything). - The 3rd method would throw a
NullPointerExceptionobviously. - The 4th and 5th methods on the contrary accept
nullbecausenullcan be cast to any type!
To remember:
nullis not an instance of any type but it can be cast to any type.
Notes
Class.getName()should not be used to perform an "is-instance-of" test becase if the object is not of typeCbut a subclass of it, it may have a completely different name and package (therefore class names will obviously not match) but it is still of typeC.- For the same inheritance reason
Class.isAssignableFrom()is not symmetric:
obj.getClass().isAssignableFrom(C.class)would returnfalseif the type ofobjis a subclass ofC.
1 Comment
You can use:
Object instance = new SomeClass(); instance.getClass().getName(); //will return the name (as String) (== "SomeClass") instance.getClass(); //will return the SomeClass' Class object HTH. But I think most of the time it is no good practice to use that for control flow or something similar...
1 Comment
Any use of any of the methods suggested is considered a code smell which is based in a bad OO design.
If your design is good, you should not find yourself needing to use getClass() or instanceof.
Any of the suggested methods will do, but just something to keep in mind, design-wise.
12 Comments
We can use reflection in this case
objectName.getClass().getName(); Example:-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getClass().getName(); } In this case you will get name of the class which object pass to HttpServletRequest interface refference variable.
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) Comments
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 [] 1 Comment
public void print(Object data) and it will still work exactly the same.class Superclass { // Superclass implementation } class Subclass extends Superclass { // Subclass implementation } public class Main { public static void main(String[] args) { Superclass obj = new Superclass(); // Check if the object is an instance of the superclass if (obj instanceof Superclass) { System.out.println("Object is an instance of Superclass"); } // Check if the object is an instance of the subclass if (obj instanceof Subclass) { System.out.println("Object is an instance of Subclass"); } else { System.out.println("Object is not an instance of Subclass"); } } } Comments
use instanceof operator to find weather a object is of particular class or not.
booleanValue = (object instanceof class) JDK 14 extends the instanceof operator: you can specify a binding variable; if the result of the instanceof operator is true, then the object being tested is assigned to the binding variable.
please visit official Java documentation for more reference.
Sample program to illustrate usage of instanceof operator :
import java.util.*; class Foo{ @Override public String toString(){ return "Bar"; } } class Bar{ public Object reference; @Override public String toString(){ return "Foo"; } } public class InstanceofUsage{ public static void main(final String ... $){ final List<Object> list = new ArrayList<>(); var out = System.out; list.add(new String("Foo Loves Bar")); list.add(33.3); list.add(404_404); list.add(new Foo()); list.add(new Bar()); for(final var o : list){ if(o instanceof Bar b && b.reference == null){ out.println("Bar : Null"); } if(o instanceof String s){ out.println("String : "+s); } if(o instanceof Foo f){ out.println("Foo : "+f); } } } } output:
$ javac InstanceofUsage.java && java InstanceofUsage String : Foo Loves Bar Foo : Bar Bar : Null