Java 程序中使用注解:注解的解析

在程序使用(解析)注解:获取注解中定义的属性值


  1. 获取注解定义的位置的对象
    (Class, Method,Field)
  2. 获取指定的注解
getAnnotation(Class)

//其实就是在内存中生成了一个该注解接口的子类实现对象
public class ProImpl implements Pro{
	public string className(){
		return "cn.abc.annotation.Demo1";
	}
	public String methodName(){
		return "show";
	}
}
  1. 调用注解中的抽象方法获取配置的属性值

Pro.java

/**
 * 描述需要执行的类名和方法名
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Pro {

    String className();
    String methodName();

}

Demo1.java

package cn.abc.annotation;

public class Demo1 {
    public void show(){
        System.out.println("demo1..show...");
    }
}

ReflectTest.java

package cn.abc.annotation;
import java.lang.reflect.Method;

/**
 * 框架类
 */
@Pro(className = "cn.abc.annotation.Demo1",methodName = "show")//想要执行Demo1里的show 方法

public class ReflectTest {
    public static void main(String[] args) throws Exception{
        /*
        可以创建任意类对象,可以执行任意方法
         */

        //1.解析注解
        //1.1获得该类的字节码文件对象
        Class<ReflectTest> reflectTestClass = ReflectTest.class;

        //2.获取上边的注解对象
        Pro an = reflectTestClass.getAnnotation(Pro.class);//获取指定注解
        //在内存中生成了一个该注解接口的子类实现对象

        //3.调用注解对象中定义的抽象方法,获取返回值
        String className = an.className();
        String methodName = an.methodName();
        System.out.println(className);//cn.abc.annotation.Demo1
        System.out.println(methodName);//show

        //4.加载该类进内存
        Class cls = Class.forName(className);
        //5.创建对象
        Object o = cls.newInstance();
        //6.获取方法对象
        Method method = cls.getMethod(methodName);
        //7.执行方法
        method.invoke(o);//demo1..show...
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值