Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if object is instanceof a parameter type

Is there a way to determine if an object is an instance of a generic type?

public <T> test(Object obj) {     if (obj instanceof T) {         ...     } } 

That clearly doesn't work. Is there an alternative? Like I want to use Java reflection to instantiate a class and then check to make sure it is of type generic T.

like image 791
Nikordaris Avatar asked Apr 20 '11 18:04

Nikordaris


People also ask

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

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

Does Instanceof work for interfaces?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.

Can I use Instanceof?

The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.


2 Answers

The only way you can do this check is if you have the Class object representing the type:

Class<T> type; //maybe passed into the method if ( type.isInstance(obj) ) {    //... } 
like image 167
Mark Peters Avatar answered Oct 16 '22 03:10

Mark Peters


To extend the sample of Mark Peters, often you want to do something like:

Class<T> type; //maybe passed to the method if ( type.isInstance(obj) ) {    T t = type.cast(obj);    // ... } 
like image 32
Puce Avatar answered Oct 16 '22 03:10

Puce