@Inherited和getAnnotation和getDeclaredAnnotations

@Inherited:指定子类可以继承父类的注解,只能是类上的注解,方法和字段的注解不能继承。即如果父类上的注解是@Inherited修饰的就能被子类继承。

package com.fyd.java.annotation;
 
import java.lang.annotation.*;
 
public class Test {
 
	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
//	@Inherited
	static @interface W{
		
	}
	
	@W
	static class A{
		
	}
	
	static class B extends A{
		
	}
	
	public static void main(String[] args) {
 
		//return inherited annotation
		System.out.println(B.class.getAnnotation(W.class));
		System.out.println(B.class.getDeclaredAnnotation(W.class));
		
	}
 
}

输出:

null

null

package com.fyd.java.annotation;
 
import java.lang.annotation.*;
 
public class Test {
 
	@Target(ElementType.TYPE)
	@Retention(RetentionPolicy.RUNTIME)
	@Inherited
	static @interface W{
		
	}
	
	@W
	static class A{
		
	}
	
	static class B extends A{
		
	}
	
	public static void main(String[] args) {
 
		//return inherited annotation
		System.out.println(B.class.getAnnotation(W.class));
		System.out.println(B.class.getDeclaredAnnotation(W.class));
		
	}
 
}

输出

@com.fyd.java.annotation.Test$W()
null

注:

getAnnotation(Class<T> annotationClass): 返回改程序元素上存在的、指定类型的注解,如果该类型注解不存在,则返回null。

getDeclaredAnnotations(Class<T> annotationClass):返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`@Inherited` 是一个标准的 Java 元注解(meta-annotation),用于指示一个注解是否可以被继承。当一个注解被标注为 `@Inherited` 后,它将可以被子类继承。 具体来说,当一个被 `@Inherited` 标注的注解被放置在一个父类上时,它将会被子类继承,并且子类上也会具有该注解。这意味着,如果我们在父类上使用了一个被 `@Inherited` 标注的注解,那么所有继承该父类的子类也将自动具有该注解。 需要注意的是,`@Inherited` 元注解仅对类级别的注解有效,对方法、字段等其他元素的注解无效。 下面是一个示例,展示了如何使用 `@Inherited` 元注解: ```java import java.lang.annotation.*; @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface MyAnnotation { // 注解元素 String value(); } ``` 在上面的示例中,我们定义了一个自定义注解 `@MyAnnotation` 并标注了 `@Inherited` 元注解。当我们将 `@MyAnnotation` 注解放置在一个父类上时,该注解将会被子类继承。 ```java @MyAnnotation("Parent") public class ParentClass { // 父类的代码内容 } public class ChildClass extends ParentClass { // 子类的代码内容 } ``` 在上面的示例中,`ChildClass` 继承自 `ParentClass`,由于 `@MyAnnotation` 使用了 `@Inherited` 元注解,所以 `ChildClass` 也会自动具有 `@MyAnnotation("Parent")` 注解。 总结一下,`@Inherited` 是一个元注解,用于指示一个注解是否可以被继承。当一个注解被标注为 `@Inherited` 后,它将可以被子类继承。但需要注意,它仅对类级别的注解有效,对其他元素的注解无效。 希望能够解答你的疑问。如果还有其他问题,请随时提问。谢谢!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值