Can I use a primitive type literal or type variable in an instanceof
expression?
class MyClass {
{
boolean b1 = null insta
Nope, because of type erasure. An instance of MyClass
doesn't actually know what T
is.
You need to have an instance of Class
. Then you can use the isInstance method. One way of doing that is to specify it in the constructor:
class MyClass
{
private Class clazz;
MyClass(Class clazz)
{
this.clazz = clazz;
}
// Now you can use clazz to check for instances, create new instances ect.
}
For the second one, the problem is the first operand, not the second. The primitive value itself isn't an instance of Integer
; the boxed version is:
Object obj = 2;
boolean b2 = obj instanceof Integer;
Whenever you've got a genuine primitive value, you'll already know the type so making a dynamic type check doesn't make much sense.