Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like instanceOf(Class<?> c) in Java?

I want to check if an object o is an instance of the class C or of a subclass of C.

For instance, if p is of class Point I want x.instanceOf(Point.class) to be true and also x.instanceOf(Object.class) to be true.

I want it to work also for boxed primitive types. For instance, if x is an Integer then x.instanceOf(Integer.class) should be true.

Is there such a thing? If not, how can I implement such a method?

like image 877
snakile Avatar asked Jun 04 '09 08:06

snakile


People also ask

What is the alternative to Instanceof in Java?

The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.

What is the difference between Instanceof and isInstance?

For instanceof you need to know the exact class at compile time. For isInstance the class is decided at run time.

What is the difference between getClass and Instanceof?

Coming to the point, the key difference between them is that getClass() only returns true if the object is actually an instance of the specified class but an instanceof operator can return true even if the object is a subclass of a specified class or interface in Java.

How do I find the instance of a class in 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 .


1 Answers

Class.isInstance does what you want.

if (Point.class.isInstance(someObj)){     ... } 

Of course, you shouldn't use it if you could use instanceof instead, but for reflection scenarios it often comes in handy.

like image 86
gustafc Avatar answered Sep 20 '22 06:09

gustafc