java注解 菜鸟_java--注解

java--注解

通常用于项目中的配置,项目中一些不常变的量,比如说域名等,还可以用于装饰者模式

eg:自定义注解

//在定义注解的时候,需要通过元注解Retention说明当前自定义注解的作用域(Class, Source, Runtime)

@Retention(RetentionPolicy.RUNTIME)

//自定义注解的时候需要使用Target说明当前的自定义注解的作用范围

@Target(ElementType.METHOD)

public @interface MyAnnotation {

public long timeout() default -1;

// 不支持自定义类型

//public MyAnn01 aa();

public Class c() default java.util.Date.class;

}

//自定义注解的使用

public class TestUserAnnotation {

static{

System.out.println("加载静态代码段");

}

@MyAnnotation(timeout = 100)

public void test01(){

System.out.println("test01");

}

@MyAnnotation(timeout = 100)

public void test02(){

System.out.println("test02");

}

@MyAnnotation(timeout = 100)

public void test03(){

System.out.println("test03");

}

@MyAnnotation(timeout = 100)

public void test04(){

System.out.println("test04");

}

public void test05(){}

}

//调用使用了自定义注解的类

public class MyJunit

{

private static Method[] methods;

public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

{

// 加载TestUserAnnotation.class 字节码文件中的方法,判断哪些方法上有自定义的注解,如果有,就执行这个方法

//1_将TestUserAnnotation.class 字节码加载到内存,class对象(代表字节码对象在内存中的对象)

Class clazz = Class.forName("com.zhujie.TestUserAnnotation");

//2_获取字节码对象上所有的方法,放回Methods数组对象,数组中每一个元素都代表Method对象(相当于字节码中的一个方法)

methods = clazz.getMethods();

//3_遍历方法

for(Method md:methods)

{

//测试方法的名称

//System.out.println(md.getName());

//判断当前方法上是否有@MyAnnotation 注解信息

//System.out.println(md.isAnnotationPresent(MyAnnotation.class));

//有就执行,否则忽略

if(md.isAnnotationPresent(MyAnnotation.class))

{

md.invoke(new TestUserAnnotation());

}

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值