让有一个类型扩展java.util.Map
:
public interface IdentifiableMap<ID, KEY, VALUE> extends Map<KEY, VALUE>{
ID getId();
}
也让有一个类型的字段,该字段在类型参数之一上声明注释(截至Java 8时可能是可能的):
private IdentifiableMap<String, @Size(min=1) String, Integer> myMap = ...;
使用Java反射API,如何从此声明中找出哪些注释已从Map
接口给出类型参数?换句话说,我想扣除为K
的CC_4类型参数提供的@Size
注释。
我知道如何从该字段的AnnotatedParameterizedType
获取类型参数的注释,但是我缺少如何将其与超级类型Map
的类型参数相关联。
不幸的是,这离容易很远。以下代码假设您想查找直接实现或扩展该类型的类型的注释,否则代码将变得更加复杂,或者在间接实现多次接口的接口问题上。<<<<<<<<<<<<<<<<<<<<<<<</p>
static Annotation[][] getActualAnnotations(AnnotatedType at, Class<?> target) {
Type[] typeParameters = target.getTypeParameters();
if(typeParameters.length==0) return new Annotation[0][];
Type t=at.getType();
Map<Type,Annotation[]> atArgAnnos;
Class<?> raw;
if(t instanceof Class) {
atArgAnnos=Collections.emptyMap();
raw=(Class<?>)t;
if(raw==target) return new Annotation[typeParameters.length][0];
}
else if(t instanceof ParameterizedType) {
ParameterizedType pt=(ParameterizedType)t;
raw=(Class<?>)pt.getRawType();
Type[] param=raw.getTypeParameters();
Annotation[][] a = Arrays
.stream(((AnnotatedParameterizedType)at).getAnnotatedActualTypeArguments())
.map(AnnotatedType::getAnnotations)
.toArray(Annotation[][]::new);
if(raw==target) return a;
atArgAnnos=new HashMap<>(a.length);
for(int ix = 0; ix < a.length; ix++)
atArgAnnos.put(param[ix], a[ix]);
}
else throw new UnsupportedOperationException(
"type variables, wildcard or arrays are not supported");
raw.asSubclass(target);// throws if not assignable
for(AnnotatedType aift: target.isInterface()? raw.getAnnotatedInterfaces():
new AnnotatedType[]{raw.getAnnotatedSuperclass()}) {
Type ift=aift.getType();
if(ift==target) return new Annotation[typeParameters.length][0]; // raw
else {
AnnotatedParameterizedType ifpt = (AnnotatedParameterizedType)aift;
if(((ParameterizedType)ifpt.getType()).getRawType()!=target) continue;
return Arrays.stream(ifpt.getAnnotatedActualTypeArguments())
.map(ta -> atArgAnnos.getOrDefault(ta.getType(), ta.getAnnotations()))
.toArray(Annotation[][]::new);
}
}
throw new UnsupportedOperationException(
t.getTypeName()+" does not (directly) extend or implement "+target);
}
它也不处理类型变量,通配符类型或数组;它已经很复杂了。但是,它处理了您的问题的示例,也是Map
的类型参数或两个都不出现在该字段类型的声明中的情况,例如
interface AnotherExample<ID, KEY> extends Map<KEY, @Size(min=100) String> {
ID getId();
}
和
AnotherExample<String, @Size(min=42) String> field;
当具有interface I<X> extends Map<X,X> {}
和字段声明I<@Size(min=10) String> field;
等类型声明时,它也可以工作,因此注释适用于键和值类型。
返回的注释对应于指定类型的类型参数;它可以像以下方式一样使用:
System.out.print(field.getName()+"t");
Annotation[][] a=getActualAnnotations(field.getAnnotatedType(), Map.class);
System.out.println("key: "+Arrays.toString(a[0])+", value: "+Arrays.toString(a[1]));