接口注解不能被实现类继承。
接口注解不能被子接口继承。
父类接口能被子类接口继承,注解需要被@Inherited元注解注释。
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestAnnotation {
}
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TestComponent {
}
public interface UserService extends UserService1 {
public void get();
}
@TestAnnotation
public interface UserService1 {
}
public class UserServiceChild extends UserServiceImpl{
}
@TestComponent
public class UserServiceImpl implements UserService {
@Override
public void get() {
}
}
class UserServiceImplTest extends BaseJunit {
@Test
void testAnnotation() {
Annotation[] annotations = UserService.class.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println("UserService的注解:" + annotations[i]);
}
annotations = UserServiceImpl.class.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println("UserServiceImpl的注解:" + annotations[i]);
}
annotations = UserServiceChild.class.getAnnotations();
for (int i = 0; i < annotations.length; i++) {
System.out.println("UserServiceChild的注解:" + annotations[i]);
}
System.out.println(UserService.class.isAnnotationPresent(TestAnnotation.class));
System.out.println(UserServiceImpl.class.isAnnotationPresent(TestAnnotation.class));
System.out.println(UserServiceImpl.class.isAnnotationPresent(TestComponent.class));
System.out.println(UserServiceChild.class.isAnnotationPresent(TestAnnotation.class));
System.out.println(UserServiceChild.class.isAnnotationPresent(TestComponent.class));
}
}
结果:
UserServiceImpl的注解:@com.o3gene.listen_jpa.test.TestComponent()
UserServiceChild的注解:@com.o3gene.listen_jpa.test.TestComponent()
false
false
true
false
true