作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想保存泛型值的类型,因为我无法在运行时获取它:
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);
}
}
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
}
}
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/
我是一名优秀的程序员,十分优秀!