单元测试中自定义注解AutoConvert无法通过反射获取的问题
问题根源:匿名内部类不会继承父类的类级注解(除非注解标注了
@Inherited) 你猜的没错!问题完全出在匿名内部类的实例化方式上。
当你用new ExampleCommandToExample() { ... }创建对象时,你其实不是在实例化ExampleCommandToExample本身,而是创建了一个它的匿名子类。默认情况下,类级别的注解不会被子类继承——除非你的@AutoConvert注解本身被标注了@Inherited元注解。
这就解释了为什么直接运行原类实例时能拿到注解,但测试里用匿名内部类就返回null:原类上的@AutoConvert并没有传递给这个匿名子类,所以this.getClass()拿到的是子类的Class对象,自然找不到注解。
解决方案
有两种可行的解决思路,你可以根据自己的需求选择:
1. 给@AutoConvert添加@Inherited元注解
修改你的自定义注解,加上@Inherited,这样子类会自动继承父类的这个类级注解:
@Retention(RetentionPolicy.RUNTIME) @Inherited // 新增这个元注解 public @interface AutoConvert { boolean enabled() default true; }
这样即使是匿名子类,通过this.getClass().getAnnotation(AutoConvert.class)也能拿到继承来的注解了。
2. 避免使用匿名内部类实例化
如果不需要继承注解的方式,你可以直接实例化原类:
exampleCommandToExample = new ExampleCommandToExample();
如果确实需要重写overideSomeMethod()方法,可以创建一个具名的子类,而不是匿名内部类:
class CustomExampleConverter extends ExampleCommandToExample { private final Type type; public CustomExampleConverter(Type type) { this.type = type; } @Override public Type overideSomeMethod() { return type; } }
然后在测试中实例化这个子类:
exampleCommandToExample = new CustomExampleConverter(type);
同样,如果你选择这个方案,记得给@AutoConvert加上@Inherited,不然具名子类也拿不到原类的注解。
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

