自定义注解校验失效:如何正确检查Java自定义注解?
自定义注解@UserException校验失效的原因及修复方案
核心问题:注解保留策略缺失
你的@UserException注解没有指定运行时保留策略,Java中注解默认的保留策略是RetentionPolicy.CLASS——这种策略下,注解仅在编译期可见,编译后的class文件中会保留注解,但运行时反射无法读取到它。这直接导致clazz.isAnnotationPresent(UserException.class)始终返回false,校验逻辑完全不执行。
修复步骤
- 给
@UserException添加@Retention(RetentionPolicy.RUNTIME)注解,确保运行时能通过反射获取到该注解:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface UserException { }
- 清理无效的校验目标
AnnotationApplyer.check()方法中传入了UserException.class(注解本身的Class对象),但注解本身属于Annotation类型,不可能继承Exception,这会产生无意义的错误输出,建议移除这个参数:
public static void check () { checkUserException(Main.class, AnnotationApplyer.class, MessageService.class, UserDefined.class); checkUserException(Printer.class, InvalidMessageException.class); }
- 修复异常处理的逻辑问题
InvalidMessageException的构造函数中调用了System.exit(0),这会导致程序直接退出,Greeter.greet()中的catch块根本无法执行。建议移除这个语句,让异常能被正常捕获处理:
@UserException class InvalidMessageException extends Exception { public InvalidMessageException (String m) { super(m); // 移除System.exit(0) } }
修正后的完整代码
import java.lang.annotation.*; @UserException // wrong placed annotation for testing @UserDefined(user = "iasonas") public abstract class Main { public static void main(String[] args) { // check annotations AnnotationApplyer.check(); // start the program new Greeter().greet(); } @UserDefined(user = "iasonas") private static class Greeter { private final String MSG = "Hello, World!"; private Printer ms = new MessageService<String>(MSG); public Greeter () { } public void greet () { try { ms.print(); } catch (InvalidMessageException e) { System.out.println("Cannot greet. "+e.toString()); } } }; }; @UserException // wrong placed annotation for testing @UserDefined(user = "iasonas") class AnnotationApplyer { public static void check () { checkUserException(Main.class, AnnotationApplyer.class, MessageService.class, UserDefined.class); checkUserException(Printer.class, InvalidMessageException.class); } public static void checkUserException (Class<?>... classes) { for (Class<?> clazz : classes) { if (!clazz.isAnnotationPresent(UserException.class)) { continue; } if (!Exception.class.isAssignableFrom(clazz)) { System.out.println("Error: "+clazz.getName()+" does not extend java.lang.Exception"); } else { System.out.println("Class "+clazz.getName()+" extends java.lang.Exception!"); } } } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface UserException { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface UserDefined { String user() default "Not specified"; } class MessageService <T> implements Runnable, Printer { private T message; private final Thread thread = new Thread(this); private int printCounter; public MessageService () { } public MessageService (T message) { this.message = message; } public T getMessage () { return message; } public void setMessage (T aMsg) { this.message = aMsg; } public int getTimes () { return printCounter; } @Override public void run () { System.out.println(message); printCounter++; } @Override public synchronized void print () throws InvalidMessageException { if (message==null) { throw new InvalidMessageException("message is null"); } thread.start(); } }; interface Printer { void print() throws InvalidMessageException; }; @UserException // well placed annotation for checking class InvalidMessageException extends Exception { public InvalidMessageException (String m) { super(m); } }
运行效果
修复后运行程序,控制台会输出:
Error: Main does not extend java.lang.Exception Error: AnnotationApplyer does not extend java.lang.Exception Error: Printer does not extend java.lang.Exception Class InvalidMessageException extends java.lang.Exception! Hello, World!
完全符合预期的校验逻辑。
内容的提问来源于stack exchange,提问作者iasonas
相关产品推荐
相关产品推荐

