如何在 class 中防止 Java 注释的多个实例
How to prevent multiple instances of a Java annotation in a class
我有这样的 Java 注释类型:
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(METHOD)
public @interface Foo {
}
我的意图是避免此注释的多个实例。换句话说,我想禁止下一个示例代码并抛出异常:
public class FooTest {
@Foo
public void method1(){...}
@Foo
public void method2(){...}
}
有什么建议吗?
实现您的意图的最佳技术(避免此注释的多个实例)是静态检查,因为它可以完成并且可以更早地检测到问题。这是通过 Java 的 annotation processing feature.
支持的
但是,该问题还表明希望在 运行 时间执行此操作,因为它包含 @Retention(RUNTIME)
并提到了例外情况。这可以通过反射轻松完成 如果要检查的 class 列表事先已知 。这是检查一个 class 的一段简单代码,因为问题提到检查单个 class。
public static void checkClass(Class<?> clazz) {
boolean used = false;
for( Method method : clazz.getDeclaredMethods() ) {
if( method.getAnnotation(Foo.class) != null ) {
if( used ) {
throw new IllegalFooUseException();
}
else { used = true; }
}
}
}
跨项目检查会更费力,因为这需要收集项目中的所有 classes,isn't so simple。
我有这样的 Java 注释类型:
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(METHOD)
public @interface Foo {
}
我的意图是避免此注释的多个实例。换句话说,我想禁止下一个示例代码并抛出异常:
public class FooTest {
@Foo
public void method1(){...}
@Foo
public void method2(){...}
}
有什么建议吗?
实现您的意图的最佳技术(避免此注释的多个实例)是静态检查,因为它可以完成并且可以更早地检测到问题。这是通过 Java 的 annotation processing feature.
支持的但是,该问题还表明希望在 运行 时间执行此操作,因为它包含 @Retention(RUNTIME)
并提到了例外情况。这可以通过反射轻松完成 如果要检查的 class 列表事先已知 。这是检查一个 class 的一段简单代码,因为问题提到检查单个 class。
public static void checkClass(Class<?> clazz) {
boolean used = false;
for( Method method : clazz.getDeclaredMethods() ) {
if( method.getAnnotation(Foo.class) != null ) {
if( used ) {
throw new IllegalFooUseException();
}
else { used = true; }
}
}
}
跨项目检查会更费力,因为这需要收集项目中的所有 classes,isn't so simple。