简体   繁体   中英

How to obtain class instance of generic argument type

In code, if I write a code line like this:

GClass<Double> x = new GClass<Double>();

And let say, that the class is like this:

public static class GClass<T> {
  private T value = null;
  public GClass() {
    // What is T? 
  }
}

Where I inserted the question "What is T?", I don't want the value (that is null ), but its type (that is Double ).

You can't find out T at execution time unless you add a constructor parameter to take Class<T> parameter and pass call it with Double.class in your case. You can then store that class and use it later.

This is due to type erasure ... basically generics are just compiler magic to insert appropriate casts and check that things should be okay.

See the Type Erasure section of the excellent Java Generics FAQ .

You might also want to read Neal Gafter's blog posts about super type tokens and type literals .

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