2

我可以在instanceof表达式中使用原始类型文字或类型变量吗?

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

我收到编译错误。有没有办法规避这些错误并在instanceof表达式中使用原始类型文字/类型变量?

基本上,我想得到保证,不,我永远无法做到这一点。

4

4 回答 4

5

不,因为类型擦除。的一个实例MyClass<T>实际上并不知道是什么T

您需要有一个Class<T>. 然后就可以使用该isInstance方法了。一种方法是在构造函数中指定它:

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.
}

对于第二个,问题是第一个操作数,而不是第二个。原始值本身不是 ; 的实例Integer。盒装版本是:

Object obj = 2;
boolean b2 = obj instanceof Integer;

每当您获得真正的原始值时,您就已经知道类型,因此进行动态类型检查没有多大意义。

于 2011-01-31T18:29:35.063 回答
2
  1. 由于类型擦除,您无法知道是什么T

  2. 文字(字符串文字除外)不是对象。
    因此,没有。

于 2011-01-31T18:30:07.670 回答
1

基本上,instanceof 要求一个对象作为左操作数。原始变量不是对象,所以不,你不能那样使用它。

于 2011-01-31T18:30:21.033 回答
0
  1. 你不能这样做。
  2. 即使你可以,你也不能使用它。

instanceof看起来像的典型用法

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

somemethod(new ArrayList());

这里重要的是你得到一个超类型的对象(这里:Collection),它可能是也可能不是子类型的实例(这里:List)。使用原语这是不可能的:

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

anothermethod(42);

在 X 点有一个 double 类型的变量 x,没有关于某些 int 42 的隐藏信息。实际参数 42 没有伪装成 double,它被转换为 double。这就是为什么 instanceof 对基元没有意义的原因。

于 2011-01-31T19:31:53.897 回答