JAVA 的注解反射机制

首先定义一个注解类

//@Target(ElementType.FIELD) :表示作用与属性上
//@Target(ElementType.METHOD) :表示作用于方法上
//也可以不写@Target() 表示作用于类上、属性或者方法上

//@Retention(RetentionPolicy.SOURCE):表示注解生存期只在源码上,编译时会被清除
//@Retention(RetentionPolicy.CLASS):表示注解生存期在编译为字节码的时候存在,但是在运行时会被清除
@Retention(RetentionPolicy.RUNTIME)  //表示注解可以一直存在
public @interface MyInject {
     int value1();
     String value2();
 }

然后测试类为:

@MyInject(value1=10,value2="dsfsdf")
public class A {
    private int a;
    private String s;
    private void f(int a){
    	++a;
    	this.a = a;
    	System.out.println(this.a+","+s);
    }
    public void print() {
    	// TODO Auto-generated method stub
    	System.out.println(a+","+s);
    }
}

Main:

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException {
        //1.先得到A的字节码
        
        A a = new A();
        Class ca = a.getClass();//获得A类的字节码
        MyInject myInject = (MyInject) ca.getAnnotation(MyInject.class);
        //2.获取A的字段a
        try {
                         
            System.out.println(myInject.toString());
            System.out.println(myInject.value1());
            System.out.println(myInject.value2());
           
            //获取a中的a、s属性和f方法
            Field declaredField = ca.getDeclaredField("a");
            Field declaredField2 = ca.getDeclaredField("s");
            Method declaredMethod = ca.getDeclaredMethod("f", int.class);
            
           //设置访问权限
            declaredMethod.setAccessible(true); //设置访问权限为true,使得可以去访问private方法
            declaredField.setAccessible(true);  //设置访问权限为true,使得可以访问private属性
            declaredField2.setAccessible(true);

            declaredField.set(a, 10);
            declaredField2.set(a,"hello");
            a.print();
            declaredMethod.invoke(a, 100); //执行a中的declardMethod方法,100为参数
        } catch (NoSuchFieldException |
                SecurityException |
         IllegalArgumentException |
           IllegalAccessException |
            NoSuchMethodException |
            InvocationTargetException e) {
              e.printStackTrace();
        }
    }
}
运行结果:

@java学习.MyInject(value1=10, value2=dsfsdf)
10
dsfsdf
10,hello
101,hello




猜你喜欢

转载自blog.csdn.net/luvalluo/article/details/80066250