java 自定义注解数组_Java——自定义注解

一,自定义注解类

@Target({ElementType.METHOD,ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Inherited //继承对接口是无用的;继承的时候只会集成到类上面的注解,不会继承到方法上的注解

@Documented

public @interface Description {

String value();

}

1,@Target:注解应用的范围,可以指定多个,这里传入一个数组;

2,@Retention:注解运行的生命周期:

wdYXSqkjMr+fQAAAABJRU5ErkJggg==

3,@Inherited:是否可以被子类继承,但是如果是标记类的话,子类不会继承此注解。

4,@Documented:生成文档中是否含有注解。

二,测试自定义注解

@Description("这个是Person接口")

public class Person {

@Description("person-name")

public String name(){return "aa";};

@Description("person-age")

public int age(){return 0;};

@Description("person-sing")

public void sing(){};

}

/*@Description("这个是Child类")*/

public class Child extends Person {

/*@Description("name")*/

public String name() {

return null;

}

/*@Description("age")*/

public int age() {

return 0;

}

/*@Description("sing")*/

public void sing() {

}

}

测试获取注解信息:

public class ParseAnno {

public static void main(String[] args) throws ClassNotFoundException {

/* 使用类加载器加载一个类 */

Class childClass = Class.forName("ShuiTian.NaiLuo.Child");

// 找到上面的 注释

boolean isPresent = childClass.isAnnotationPresent(Description.class);

if (isPresent) {

// 拿到注解实例

Description d = (Description) childClass

.getAnnotation(Description.class);

System.out.println(d.value());

}

// 找到方法上的注解

Method[] methods = childClass.getDeclaredMethods();

for (Method md : methods) { // 遍历此类的方法

if (md.isAnnotationPresent(Description.class)) { // 如果方法上存在Description注解,则获取值信息

Description d = (Description) md

.getAnnotation(Description.class);

System.out.println(d.value());

}

}

System.out.println("---------高能分隔符----------");

/* 另一种解析方法上注解的方法 */

for (Method md : methods) { // 遍历此类的方法

Annotation[] as = md.getAnnotations(); //获取此方法上的注解

for (Annotation anno : as) {

if (anno instanceof Description) {

Description d = (Description) anno;

System.out.println(d.value());

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值