简体   繁体   中英

get instantiated type variable in java

I would like to check if the instantiated type of a generic class has certain properties, eg:

class Foo<T> {
  void bar () { 
    if (T instanceof Serializable)   // does not compile
      ...
  } 
}

I am wondering if the generic information is totally lost during runtime? And does that mean there is no way to accomplish what I would like to do?

And does that mean there is no way to accomplish what I would like to do?

You can write:

class Foo<T> {
  private final Class<T> clazz;

  Foo (final Class<T> clazz) { // require creator to supply a Class<T>
    this.clazz = clazz;
    if (clazz == null) {
      throw new NullPointerException();
    }
  }

  void bar () { 
    if (Serializable.class.isAssignableFrom(clazz)) {
      ...
    }
  } 
}

You are right, generic type information is lost at run-time. It's called Type Erasure .Compiler would remove all the generic type and do the cast's(if necessary) at run time. and all the

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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