我有一个返回 List<Property<?>>
的方法.
属性是一种具有一个泛型参数的类型:
public class Property<T extends Comparable<T>> { ... }
有一个混合类型属性列表,我无法知道特定元素具有什么类型参数。
我想做这样的事情:
List<Property<?>> list = getList();
for(Property<?> crt : list)
{
PropertyWrapper<?> crtWrapper = new PropertyWrapper(crt.getGenericType());
// I know this doesn't exist ----^
}
一句话:我需要PropertyWrapper
具有与当前 Property
相同的通用模板参数做。是否有任何方法可以做到这一点?
我可以应用 https://stackoverflow.com/a/3437930/146003 中所述的建议但即使我这样做,如何实例化适当的 PropertyWrapper<XXX>
然后,只有一个 Class<T>
的实例?
我可以修改Property<?>
如果需要的话。我也不介意是否需要使用反射(我认为它需要)
编辑:我忘记了什么。事实上,我无法通过行来实例化包装器
PropertyWrapper<?> crtWrapper = new PropertyWrapper(crt.getGenericType());
因为我有专门的子类 ( PropertyWrapper_String
)。
现在我看到了两种可能性:
1:通过字符串实例化类:
String strGenericType = "";
Class<?> wrapperClass = Class.forName("PropertyWrapper_" + strGenericType);
2:有没有什么方法可以在不创建子类的情况下专门化泛型类?
非常感谢您的提示
最佳答案
尝试创建以下方法:
<T> PropertyWrapper<T> createWrapper(Property<T> property){
return new PropertyWrapper<T>(property);
}
然后这样调用它。
List<Property<?>> list = getList();
for(Property<?> crt : list)
{
PropertyWrapper<?> crtWrapper = createWrapper(crt);
}
上述工作的原因是通用类型 T
从参数中推断出来,并在整个方法中被锁定。不像使用 <?>
在 <?>
的每个实例所在的循环中被推断为不同的类型。
编辑:
要处理根据包装器中的类而具有不同类类型的问题,请考虑一个 Map,其中键是被包装的类,值是包装器。
Map<Class<?>, Class<?>> myMap;
然后你可以这样:
Class<?> wrappedType = property.getGenericType();
Class<?> wrapperClass = myMap.get(wrappedType);
PropertyWrapper<?> wrapper = (PropertyWrapper<?>) wrapperClass.newInstance();
尽管如果您需要传递一个参数,您可能需要这样做。
Constructor<?> constructor = wrapperClass.getDeclaredConstructor(property.getClass());
PropertyWrapper<?> wrapper = (PropertyWrapper<?>) constructor.newInstance(property);
关于java - 泛型:获取实例名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9160543/