gpt4 book ai didi

Java 元编程难题 : get all annotations that are themselves annotated by a given annotation A

转载 作者:搜寻专家 更新时间:2023-11-01 01:58:52 27 4
gpt4 key购买 nike

你觉得你是java高手吗?

您是否深谙反射 API 的 secret ?

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);
}

您必须编写方法 solve,以便在方法 C.x() 和 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);
}

我想这只是回避了为什么 annotationType() 有效而 getClass() 无效的问题。

关于Java 元编程难题 : get all annotations that are themselves annotated by a given annotation A,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1359452/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com