gpt4 book ai didi

java - 获取泛型类的 .class 对象

转载 作者:行者123 更新时间:2023-12-04 10:55:46 24 4
gpt4 key购买 nike

我想保存泛型值的类型,因为我无法在运行时获取它:

public class A<T> {
private final Class<T> genericType;
public A(Class<T> genericType) {
this.genericType = genericType;
}

public Class getGenericType() {
return genericType;
}
}


现在要创建子类,我按如下方式使用它:
public class B extends A<String> {
public B() {
super(String.class);
}
}

注意 super() 的参数类型匹配(通过编译时间检查)到 A 的泛型类型。
这很好用。但是如果我想用 Map 来拥有它,我就无法获得正确的类对象:
public class C extends A<Map<String, String>> {
public C() {
super(Map.class); // does not match Map<String,String>
super(Map<String,String>.class) // no valid java expression, i dont know what
}
}

Sooo有人有帮助我摆脱这种痛苦的提示吗?
我目前能做的最好的事情就是放弃 A 中的强类型:
public class A<T> {
// old: private final Class<T> genericType;
private final Class genericType; // note the missing generic
public A(Class genericType) { // here as well
this.genericType = genericType;
}

public Class getGenericType() {
return genericType;
}
}

最佳答案

我不确定这是否满足您的要求,但您可以执行以下类似操作,请参阅 How to get the class of a field of type T?

import java.lang.reflect.*;
import java.util.*;


public class GenericTypeTest{

public static void main(String []args){
B b = new B();
System.out.println("B is a " + b.getGenericType());
C c = new C();
System.out.println("C is a " + c.getGenericType());
}
}


class A<T> {
public Class getGenericType() {
Object genericType = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
if(genericType instanceof ParameterizedType){
genericType = ((ParameterizedType)genericType).getRawType();
}
return (Class<T>) genericType;
}
}



class B extends A<String> {
}

class C extends A<Map<String,String>> {
}

这将得到类似的输出
B is a class java.lang.String
C is a interface java.util.Map

关于java - 获取泛型类的 .class 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59210863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com