Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

java - 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...