注解与反射

注解@Interface
@Retention 注解可以保留多长时间:
RetentionPolicy.SOURCE:Annotation只保留在源代码中,编译器编译时,直接丢弃这种Annotation。
RetentionPolicy.CLASS:编译器把Annotation记录在class文件中。当运行Java程序时,JVM中不再保留该Annotation。
RetentionPolicy.RUNTIME:编译器把Annotation记录在class文件中。当运行Java程序时,JVM会保留该Annotation,程序可以通过反射获取该Annotation的信息。
@Target指定Annotation用于修饰哪些程序元素。
ElementType.TYPE:能修饰类、接口或枚举类型
ElementType.FIELD:能修饰成员变量
ElementType.METHOD:能修饰方法
ElementType.PARAMETER:能修饰参数
ElementType.CONSTRUCTOR:能修饰构造器
ElementType.LOCAL_VARIABLE:能修饰局部变量
ElementType.ANNOTATION_TYPE:能修饰注解
ElementType.PACKAGE:能修饰包
@Documented
如果定义注解A时,使用了@Documented修饰定义,则在用javadoc命令生成API文档后,所有使用注解A修饰的程序元素,将会包含注解A的说明。
@Inherited指定Annotation具有继承性。
父类使用过注解,子类即使不直接使用注解,也会拥有注解。
反射
主要方法有:
1、isAnnotationPresent(Class<? extends Annotation> annotationClass):判断该程序元素上是否存在指定类型的注解,如果存在则返回true,否则返回false。
2、getAnnotation(Class annotationClass):返回该程序元素上存在的指定类型的注解,如果该类型的注解不存在,则返回null
3、Annotation[] getAnnotations():返回该程序元素上存在的所有注解。

package com.demo1;
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 MyTag {
 
}
package com.demo1;
 
import java.lang.reflect.Method;
 
public class ProcessTool {
    public static void process(String clazz) {
        Class targetClass = null;
 
        try {
            targetClass = Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
 
        for (Method m : targetClass.getMethods()) {
            if (m.isAnnotationPresent(MyTag.class)) {
                System.out.println("被MyTag注解修饰的方法名:" + m.getName());
            } else {
                System.out.println("没被MyTag注解修饰的方法名:" + m.getName());
            }
        }
    }
}

测试类

package com.demo1;
 
public class Demo {
    public static void m1() {
 
    }
 
    @MyTag
    public static void m2() {
 
    }
}
 
package com.demo1;
 
public class Test {
 
    public static void main(String[] args) {
        ProcessTool.process("com.demo1.Demo");
    }
}

运行结果为:
没被MyTag注解修饰的方法名:m1
被MyTag注解修饰的方法名:m2
没被MyTag注解修饰的方法名:wait
没被MyTag注解修饰的方法名:wait
没被MyTag注解修饰的方法名:wait
没被MyTag注解修饰的方法名:equals
没被MyTag注解修饰的方法名:toString
没被MyTag注解修饰的方法名:hashCode
没被MyTag注解修饰的方法名:getClass
没被MyTag注解修饰的方法名:notify
没被MyTag注解修饰的方法名:notifyAll
getMethods():返回类的所有的共有方法
getDeclaredMethods():返回类的所有的方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值