In Java, can I use a primitive type literal or type variable in an instanceof expression?

后端 未结 4 1806
后悔当初
后悔当初 2021-01-07 03:11

Can I use a primitive type literal or type variable in an instanceof expression?

class MyClass {
    {
         boolean b1 = null insta         


        
4条回答
  •  無奈伤痛
    2021-01-07 03:50

    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.

提交回复
热议问题