获取类的方法上的所有方法上的注解(二)

接着上面的例子,实现获取具体注解的值


Anno.java注解的实现类,这里加入了属性value,便于在使用的Anno注解的时候可以,如此使用@Anno("coding"),这里还设置了注解的默认值。

其实也可以设置其他的属性。

package com.robot.test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Anno {
	public String value() default "hello";
}

Student.java使用注解的类。可以看到这里直接在注解上加上了@Anno("Student get the age!")形式,如果Anno注解的属性并不是value,则需要写成:

@Anno(attr="Student get the age!")类似的形式,具体请参考相关注解的详细内容。

package com.robot.test;

public class Student {
	public int age;
	public String name;
	
	@Anno("Student get the age!")
	public int getAge() {
		return age;
	}
	@Anno("Student set the age!")
	public void setAge(int age) {
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}


AnnotationTest.java测试类:


package com.robot.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class AnnotationTest {
	public static void main(String[] args) {
		
		Method[] methods = Student.class.getMethods();
		
		for (Method method : methods) {
			Annotation[] annotations = method.getAnnotations();
			for (Annotation annotation : annotations) {
				// 获取注解的具体类型
				Class<? extends Annotation> annotationType = annotation.annotationType();
				if (Anno.class == annotationType) {
					// 方式一:获取注解的具体的值
					// Anno an = (Anno)annotation;
					// System.out.println(an.value());
					// 方式二:获取注解的具体的值
					Anno anno = (Anno) annotationType.cast(annotation);
					System.out.println(anno.value());
					
					System.out.println(method.getName()+"()\t" + Anno.class.getName());
					
					// 打印出java.lang.annotation.Annotation,注解类其实都实现了Annotation这个接口
					Class<?>[] interfaces = Anno.class.getInterfaces();
					System.out.println(interfaces[0].getName());
				}
			}
		}
	}
}

打印:

Student get the age!
getAge()	com.robot.test.Anno
java.lang.annotation.Annotation
Student set the age!
setAge()	com.robot.test.Anno
java.lang.annotation.Annotation


从上图可以看出这里就获取了Student的方法上注解的具体的值了,实际项目中可以根据具体的值进行相关的操作。


具体详细的内容可以参考这篇博客:

http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值