java注解

 自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited

public @interface Test{
  public int id();
  public String description() default "no description";
}

@Documented的目的就是让这一个Annotation类型的信息能够显示在javaAPI说明文档上,

@Inherited需要把Annotation的数据继承给子类

@Target里面的ElementType是用来指定Annotation类型可以用在哪一些元素上的

@Retention设置为RUNTIME表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到JVM中去的.

下面是一个使用注解和解析注解的实例

package Test_annotation;
import java.lang.reflect.Method;
public class Test_1 {

@Test(id =1,description="hello method_1")
public void method_1() {
}

@Test(id = 2)
public void method_2() {
}

@Test(id=3,description="last method")
public void method_3() {
}

public static void main(String[] args) {
Method[] methods = Test_1.class.getDeclaredMethods();
for (Method method : methods) {

boolean hasAnnotation = method.isAnnotationPresent(Test.class);
if (hasAnnotation) {

Test annotation = method.getAnnotation(Test.class);
System.out.println("Test( method = " + method.getName()
+ " , id = " + annotation.id() + " , description = "
+ annotation.description() + " )");
}
}
}
}


 

输出结果如下:
Test( method = method_1 , id = 1 , description = hello method_1 )
Test( method = method_2 , id = 2 , description = no description )
Test( method = method_3 , id = 3 , description = last method )

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值