fly*_*ire 4 java puzzle annotations metaprogramming
你认为你是一个java向导吗?
您是否精通反射API的秘密?
public @interface @a {}
public @interface @b {}
@Mark public @interface @c {}
@Mark public @interface @d {}
public @interface @e {}
public Class C
{
@a @b @c @d @e public void x();
}
public class Solver
{
public Annotation[] solve(Method m, Class c);
}
Run Code Online (Sandbox Code Playgroud)
你必须编写方法求解,所以如果在方法Cx()和Mark.class上调用它,它将返回{c,d}.
(这不是家庭作业,是我正在尝试开发的框架元编程框架的真正编程任务)
这是经过测试的.它确实比应该的更难.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface a{}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface b{}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface Mark{}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Mark
public @interface c{}
public static class D {
@a @b @c
public void x() {}
}
public static void main(String[] args) throws Exception {
Method m = D.class.getMethod("x");
Collection<Annotation> ret = new HashSet<Annotation>();
Annotation[] annotations = m.getAnnotations();
for (Annotation annotation : annotations) {
Annotation subAnnots = annotation.annotationType().getAnnotation(Mark.class);
if (subAnnots != null) {
ret.add(annotation);
}
}
System.out.println(ret);
}
Run Code Online (Sandbox Code Playgroud)
我想它只是引出了为什么annotationType()工作的问题,但是getClass()没有.