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 .
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!
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 .
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.
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 );
Volvo v = new Volvo(); if (v instanceof Volvo) { System.out.println("I'm boxy, but safe."); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With