关于Annotation:inherited学习

JDK默认父类的注解不会被子类继承,要想被子类继承,需要在自定义注解加上 java.lang.annotation.Inherited型态的Annotation。

同时以下几个方面需要注意:

1)子类继承是一个父类的类型是一个类,而不是一个接口,在接口中定义的注解不会被子类继承,以下可证明

//注解类的定义: 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<InhertiedChild> 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");
}
}
}


运行以上代码:输出为:"it doesn't existed in subClass",知道如果接口定义注解,即使子类继承该接口,也不会存在接口中的注解
2)将父类定义为类,子类用extends关键字,即可输出:It is inherited by subClass。获得我们想要的结果
3)注解定义在方法上,一种情况是子类覆盖父类的方法,另一种情况是子类没有覆盖父类的方法,在这里只对第二种情况验证,[b]说明一下,当子类覆盖父类的方法时,父类方法上注解不会被子类继承,读者可自己去验证。[/b]


//自定义的注解类: 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<InhertiedChild> 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");
}
}

}


输出结果为:"It is inherited by subClass method”,证明该注解被子类方法继承
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值