繁体   English   中英

从通用列表类型中获取Java类名称

[英]Get Java Class name from generic List type

我有一个方法,里面有1个List,泛型类:

public static String classTypeOfList(List<T> list) {
    return T.getName(); //in my mind...
}

代码是错误的,但你可以看到,我想要的。 如果我这样称呼这个方法:

List<MyObject> list;
System.out.println("the type of the list is: "+classTypeOfList(list));

我想得到这个结果:

the type of the list is: MyObject

我怎么能得到泛型类的名字? 或者,如果我不能这样做,那么你能告诉我另一种选择吗? 谢谢!

由于Type Erasure ,你将无法获得类型(如果是空列表)。正如JLS所说的类型擦除:

4.6。 类型擦除

类型擦除是从类型(可能包括参数化类型和类型变量)到类型(从不参数化类型或类型变量)的映射。 我们写| T | 用于擦除类型T.擦除映射定义如下:

 The erasure of a parameterized type (§4.5) G<T1,...,Tn> is |G|. The erasure of a nested type TC is |T|.C. The erasure of an array type T[] is |T|[]. The erasure of a type variable (§4.4) is the erasure of its leftmost bound. The erasure of every other type is the type itself. 

类型擦除还将构造函数或方法的签名(第8.4.2节)映射到没有参数化类型或类型变量的签名。 构造函数或方法签名s的擦除是由与s相同的名称和s中给出的所有形式参数类型的擦除组成的签名。

如果构造函数或方法的签名被擦除,则构造函数或方法的类型参数(第8.4.4节)以及方法的返回类型(第8.4.5节)也会被擦除。

擦除泛型方法的签名没有类型参数。

如果是非空清单:

......
public static void main(String[] args) throws ClassNotFoundException {

List<MyObject> list= new ArrayList<MyObject>();
        list.add(new MyObject());
        System.out.println("the type of the list is: "+classTypeOfList(list));
}

public static <T> String classTypeOfList(List<T> list) throws ClassNotFoundException {
        return list.get(0).getClass().getCanonicalName(); 
}

OUTPUT

the type of the list is: MyObject

我担心,这是不可能做到的。 泛型仅在编译时存在。 在运行时,此信息将被删除,并且在运行时, List<MyObject>将简单地变为List

这个答案可能与问题很少(或非常)不同,因为评论的时间足够长,所以我将其作为答案发布。

我发现这个问题很有趣,因此尝试了一下。 我的尝试是跟随,我得到了班级的Type ,所以我认为值得分享并获得专家意见回到我的方法

public class A {
    public static void main(String[] args) {

    List<B> listB = new ArrayList<>();
    B b1 = new B();
    listB.add(b1);

    List<C> listC = new ArrayList<>();
    C c1 = new C();
    listC.add(c1);

    A a = new A();
    a.method(listB);
    a.method(listC);

}

public <T> void method(List<T> list) {

    System.out.println(list.get(0).getClass().getName());
}
}

class B {

}

class C {

}

我得到的输出是BC

您需要在对象上使用getClass() 获得类对象后,可以使用getName()来检索类名。

这是你如何上课:

Class<T> clazz = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);

您可以在此链接上阅读更多相关信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM