简体   繁体   English

Java-instanceof vs运行时泛型类的转换:

[英]Java - instanceof vs Casting of Generic class at runtime:

In the code extracted from Java Complete Reference by Herbert Schildt: 在Herbert Schildt从Java完整参考摘录的代码中:

class Gen<T> {
  T obj;

  Gen(T o) {
    ob = o;
  }

  T getob() {
    return ob; 
  }
}

class Gen2<T> extends Gen<T> {
  Gen2(T o) {
    super(o);
  }
}

class Test {
  public static void main(String args[]) {
    Gen2<Integer> obj = new Gen2<Integer>(99);
  }
}

he mentions that instanceof can't verify if a object is from a typed generic class at runtime because no Generic information is available: 他提到instanceof无法在运行时验证对象是否来自类型化的泛型类,因为没有泛型信息可用:

if (obj instanceof Gen2<Integer>) // illegal, doesn't compile

you can only use 你只能用

if (obj instanceof Gen2<?>) // legal

However, you can still Cast the same object to (Gen) as long as it is compatible: 但是,只要兼容,您仍可以将同一对象投射到(Gen):

(Gen<Integer>) obj // legal

but: 但:

(Gen<Long>) obj // illegal

Isn't this a Java contradiction? 这不是Java的矛盾吗? If Java knows that obj can be cast to a Gen at runtime, why doesn't it knows that obj is an instanceof Gen class/subclass? 如果Java知道可以在运行时将obj强制转换为Gen,那么为什么不知道obj是Gen类/子类的实例呢?

I read the book, confused by this too, I found this, maybe helpful: https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#cannotCast 我读了本书,对此也感到困惑,我发现这可能对您有所帮助: https : //docs.oracle.com/javase/tutorial/java/generics/restrictions.html#cannotCast

However, in some cases the compiler knows that a type parameter is always valid and allows the cast. 但是,在某些情况下,编译器知道类型参数始终有效并允许强制转换。 For example: 例如:

 List<String> list1 = ...; ArrayList<String> list2 = (ArrayList<String>)list1; // OK 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM