Java – gets the generic type of the “real” class
•
Java
How do I get a "real" class of a generic type?
For example:
public class MyClass<T> { public void method(){ //something System.out.println(T.class) //causes a compile error,I wont the class name //something } }
If t = integer
Output:
java.lang.Integer
If t = string
Output:
java.lang.String
thank you
Solution
If you have an instance variable of type T in your class and it happens to be set, you can print the class of the variable
public class Test<T> { T var; public static void main(String[] args) { Test<Integer> a = new Test<Integer>(); System.out.println(a.boo()); a.setVar(new Integer(10)); System.out.println(a.boo()); } public String boo() { if (var == null) { return "Don't kNow yet"; } return var.getClass().getSimpleName(); } public void setVar(T var) { this.var = var; } public T getVar() { return var; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码