Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - How do I check if my object is of type of a given class?

Tags:

My method gets Class as a parameter and I have to check that one my variables is of type class.

Volvo v1 = new Volvo(); Class aClass = v1.getClass(); check(aClass); 

inside I need to do something like

   v2 instanceof aClass  ? "True" : "False"); 

but this doesn;t compile .

like image 771
Bick Avatar asked Sep 21 '14 16:09

Bick


People also ask

How do you check if an object is a type of class?

Use the instanceof operator to check if an object is an instance of a class, e.g. if (myObj instanceof MyClass) {} . The instanceof operator checks if the prototype property of the constructor appears in the prototype chain of the object and returns true if it does. Copied!

How do you check if an object is of a certain type Java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

Is an object a type of class?

an object is an element (or instance) of a class; objects have the behaviors of their class. The object is the actual component of programs, while the class specifies how instances are created and how they behave.


2 Answers

I think you want aClass.isInstance( v2 ). The docs say it works the same as the instanceOf keyword. I guess they can't use instanceOf as a method name because keywords can't be used as method names.

v2 = ??? Volvo v1 = new Volvo(); Class aClass = v1.getClass(); aClass.isInstance( v2 )       // "check(aClass)" 

Or maybe just use a class literal, if "Volvo" is a constant.

v2 = ??? Volvo.class.isInstance( v2 ); 
like image 73
markspace Avatar answered Sep 21 '22 13:09

markspace


    Volvo v = new Volvo();     if (v instanceof Volvo) {         System.out.println("I'm boxy, but safe.");     } 
like image 27
cjcdoomed Avatar answered Sep 23 '22 13:09

cjcdoomed