Java 所有自定义批注都有一个通用的基类型
因此,我创建了几个自定义注释:Java 所有自定义批注都有一个通用的基类型,java,inheritance,reflection,annotations,java-annotations,Java,Inheritance,Reflection,Annotations,Java Annotations,因此,我创建了几个自定义注释: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Foo { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Bar { } 这些注释在我的函数中使用: public class Worker { @Foo pu
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Foo {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {
}
这些注释在我的函数中使用:
public class Worker {
@Foo
public void doTaskOne() {...}
@Bar
public void doTaskX() {...}
...
}
我想使用java反射来检查某个注释是否在一个方法中声明
for (Method m : methods) {
if (m.isAnnotationPresent(Foo.class)) {
...
} else if (m.isAnnotationPresent(Bar.class)) {
...
}
}
问题在于,由于在Java中,自定义注释@接口
无法扩展。我的意思是这是非法的:
public @interface Bar extends MyBaseAnnotation{
}
这就是我无法为所有自定义注释类Foo
和Bar
提供基本@接口的原因。所以,如果我创建了一个新的自定义注释,我需要在上面的方法检查代码中添加更多的else if
条件,这太糟糕了!有没有办法解决这个问题?我想要实现的是将我的方法检查代码推广到:
for (Method m : methods) {
if (m.isAnnotationPresent(MyBaseAnnotation.class)) {
...
}
}
如何实现它?您可以使用基本自定义注释对自定义注释进行注释,就像do一样
而不是:
public@接口栏扩展MyBaseAnnotation{
}
使用:
@MyBaseAnnotation
公共@接口栏{
}
假设
@Parent
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Foo {}
@Parent
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Bar {}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
@interface Parent {}
还有一种方法
public static boolean isAnnotationPresent(Method method, Class<? extends Annotation> parentAnnotation) throws NoSuchMethodException {
for (Annotation methodAnnotation : method.getDeclaredAnnotations()) {
if (methodAnnotation.annotationType().isAnnotationPresent(parentAnnotation)) {
return true;
}
}
return false;
}
您答对了:Java中注释类型之间没有继承。不过,你可以制定自己的规则。通过说“如果注释B上面有注释A,那么B扩展了A”,您定义了使用反射时要遵循的规则 注释的注释?我应该如何在我的方法检查方法中使用这个策略?使用一个简单的助手方法,就像@AndrewTobilko在他的回答中显示的那样。如果您使用的是Spring,那么您可以看看父注释中是否有方法,以便方法检查函数可以为所有注释调用它?换句话说,所有“继承的”注释都继承此方法吗public@interface Parent{String value()default”“;}
No,您可以尝试使用/复制Spring使用的类似机制,但这是一个相当复杂的机制,需要创建自己的注释API,并在运行时使用自己的代理类实现自己的注释。这样,当使用api方法时,您就可以从父注释中读取数据并将其复制到子注释中。但在任何情况下,我都不会提出这种骇人的解决方案。也许可以试着简化注释的使用。但是如果你想这样做@Leem.fin,我可以试着提供更多帮助
isAnnotationPresent(m, Parent.class)