我有一个任意的Java bean,如下所示:
class SomeBean {
public Map<String, SomeOtherBean> getOtherBeans() { ... }
public void setOtherBeans(Map<String, SomeOtherBean> otherBeans) { ... }
}
,我想用泛型方法提取类型SomeOtherBean
。在Java的类型擦除的存在下,这是可能的吗?
是的,这是可能的,即使在游戏中有擦除。
以下实现来自Magnolia的TypeMappingImpl
[1] (GPL和Magnolia网络协议下的双重许可)从setter方法中提取到第一级的所有类型参数:
private List<Class<?>> inferGenericTypes(Method method) {
List<Class<?>> inferredTypes = new ArrayList<Class<?>>();
Type[] parameterTypes = method.getGenericParameterTypes();
for (Type parameterType : parameterTypes) {
if (parameterType instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) parameterType;
for (Type t : type.getActualTypeArguments()) {
if (t instanceof ParameterizedType) {
// this the case when parameterized type looks like this: Collection<List<String>>
// we care only for raw type List
inferredTypes.add((Class<?>) ((ParameterizedType) t).getRawType());
} else if (t instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) t;
if (wildcardType.getUpperBounds().length > 0) {
// upper bounds (? extends Number)
inferredTypes.add((Class<?>) wildcardType.getUpperBounds()[0]);
} else {
// lower bounds (? super Number)
inferredTypes.add((Class<?>) wildcardType.getLowerBounds()[0]);
}
} else {
inferredTypes.add((Class<?>) t);
}
}
}
}
return inferredTypes;
}
[1]: from package info.magnolia.jcr.node2bean.impl