【问题标题】:In Java, can I use a primitive type literal or type variable in an instanceof expression?在 Java 中,我可以在 instanceof 表达式中使用原始类型文字或类型变量吗?
【发布时间】:2011-01-31 18:26:06
【问题描述】:

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

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

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

基本上,我想放心,不,我永远做不到。

【问题讨论】:

    标签: java instanceof


    【解决方案1】:

    不,因为类型擦除MyClass&lt;T&gt; 的实例实际上并不知道 T 是什么。

    您需要有一个Class&lt;T&gt; 的实例。然后你可以使用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;
    

    只要你有一个真正的原始值,你就已经知道它的类型,所以进行动态类型检查没有多大意义。

    【讨论】:

      【解决方案2】:
      1. 由于类型擦除,您无法知道T 是什么。

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:
          1. 你做不到。
          2. 即使可以,也无法使用。

          instanceof 的典型用法如下所示

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

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

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-04-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多