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
.
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.
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.
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.
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) ) { //... }
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); // ... }
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