Get “real” class of generic type

前端 未结 5 697
傲寒
傲寒 2021-02-02 16:33

How can I get the \"real\" class of a generic type?

For Example:

public class MyClass {
    public void method(){
        //something

        S         


        
5条回答
  •  不要未来只要你来
    2021-02-02 17:32

    If you have a instance variable of type T in your class, and it happens to be set, then you could print the class of that variable.

    public class Test {
    
        T var;
    
        public static void main(String[] args) {
            Test a = new Test();
            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;
        }
    }
    

提交回复
热议问题