获取类的方法上的所有方法上的注解

最近在加深注解这块的理解,很多框架都使用到了注解。

直接上代码:


注解的实现类

Anno.java

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 {

}



使用注解的类
Student.java

package com.robot.test;

public class Student {
	public int age;
	public String name;
	
	@Anno
	public int getAge() {
		return age;
	}
	@Anno
	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) {
					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());
				}
			}
		}
	}
}

总结:可以看到注解基本上会结合反射来做,也间接提现了反射的重要性了。

    上面的例子中,注解的类Anno.java中并没有写出这个注解的方法,所以还不算一个完整的例子。

    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值