---
title: "关于Annotation:inherited学习"
author: "shadabing"
date: "2010-04-19T23:01:20Z"
tags: ["JDK", "Java"]
categories: ["编程语言"]
slug: "annotation-inherited"
draft: false
lastmod: "2010-04-21T00:31:11Z"
id: 647893
url: "https://shadabing.iteye.com/blog/647893"
---

JDK默认父类的注解不会被子类继承，要想被子类继承，需要在自定义注解加上 java.lang.annotation.Inherited型态的Annotation。 同时以下几个方面需要注意： 1）子类继承是一个父类的类型是一个类，而不是一个接口，在接口中定义的注解不会被子类继承，以下可证明 \[code="java"] //注解类的定义： InheritedAnonation.java import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Inherited //能通过反射读取 @Retention(RetentionPolicy.RUNTIME) public @interface InheritedAnonation { String value() default "MyAnnotation"; } //接口类的定义：SuperClass.java @InheritedAnonation public interface SuperClass { } //继承接口的子类定义:InhertiedChild.java public class InhertiedChild implements SuperClass { } //测试类的定义:TestInherited.java import java.lang.reflect.Method; public class TestInherited { public static void main(String\[] args)throws SecurityException,NoSuchMethodException { Class inheritedChild = InhertiedChild.class; if(inheritedChild.isAnnotationPresent(InheritedAnonation.class)) { System.out.println("It is inherited by subClass"); } else { System.out.println("it doesn't existed in subClass"); } } } \[/code] 运行以上代码：输出为："it doesn't existed in subClass",知道如果接口定义注解，即使子类继承该接口，也不会存在接口中的注解 2)将父类定义为类，子类用extends关键字，即可输出：It is inherited by subClass。获得我们想要的结果 3)注解定义在方法上，一种情况是子类覆盖父类的方法，另一种情况是子类没有覆盖父类的方法，在这里只对第二种情况验证，\[b]说明一下，当子类覆盖父类的方法时，父类方法上注解不会被子类继承，读者可自己去验证。\[/b] \[code="java"] //自定义的注解类： InheritedAnonation.java import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface InheritedAnonation { String value() default "MyAnnotation"; } //父类的定义：SuperClass.java public class SuperClass { @InheritedAnonation public void sayHello() { } } //子类定义:InhertiedChild.java public class InhertiedChild extends SuperClass { } //测试类的定义 import java.lang.reflect.Method; public class TestInherited { public static void main(String\[] args) throws SecurityException, NoSuchMethodException { Class inheritedChild = InhertiedChild.class; //通过反射根据名称获取相应的方法 Method method = inheritedChild.getMethod("sayHello", new Class\[]{}); if(method.isAnnotationPresent(InheritedAnonation.class)) { System.out.println("It is inherited by subClass method"); } else { System.out.println("it doesn't existed in subClass method"); } } } \[/code] 输出结果为："It is inherited by subClass method”，证明该注解被子类方法继承