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

六眼飞鱼酱① 提交于 2019-11-30 20:06:41

问题


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

class MyClass<T> {
    {
         boolean b1 = null instanceof T; // T erasure -> Object should be used
         boolean b2 = 2 instanceof Integer; // Incompatible operands
    }

I'm getting compilation errors. Is there any way to circumvent these errors and use a primitive type literal/type variable in an instanceof expression?

Basically, I want to be reassured that no, I will never be able to do that.


回答1:


Nope, because of type erasure. An instance of MyClass<T> doesn't actually know what T is.

You need to have an instance of Class<T>. Then you can use the isInstance method. One way of doing that is to specify it in the constructor:

class MyClass<T>
{
    private Class<T> clazz;

    MyClass(Class<T> 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.




回答2:


  1. Due to type erasure, you cannot know what T is.

  2. Literals (except for string literals) aren't objects.
    Therefore, no.




回答3:


Basically, instanceof askes for an object as left operand. Primitive variables are not objects, so no, you can't use it that way.




回答4:


  1. You can't do it.
  2. Even if you could, you can't use it.

A typical usage of instanceof looks like

void somemethod(Collection c) {
    if (c instanceof List) {...}
}

somemethod(new ArrayList());

The important thing here is that you get an object of a supertype (here: Collection) which may or may not be instance of a subtype (here: List). With primitives this is impossible:

void anothermethod(double x) {
    .... // <------ X
}

anothermethod(42);

At the point X there's a variable x of type double, there's no hidden information about some int 42. The actual parameter 42 didn't masquerade as double, it's got converted to a double. That's why instanceof makes no sense for primitives.



来源:https://stackoverflow.com/questions/4854546/in-java-can-i-use-a-primitive-type-literal-or-type-variable-in-an-instanceof-ex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!