本文介绍了获得“真实”泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得泛型类型的真实类?



例如:

  public class MyClass< T> {
public void method(){
// something

System.out.println(T.class)//导致编译错误,我不会使用类名

//某事
}
}

如果T =整数

输出:

  java.lang.Integer 

如果T = String

输出: p>

  java.lang.String 

Thanks

解决方案

如果在类中有类型T的实例变量,设置,那么你可以打印该变量的类。

  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){
returnDo not know yet;
}
return var.getClass()。getSimpleName();
}

public void setVar(T var){
this.var = var;
}

public T getVar(){
return var;
}
}


How can I get the "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

Thanks

解决方案

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> {

    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;
    }
}

这篇关于获得“真实”泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:29