自定义注解 + 反射的实现

package com.myspringboot.test;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/*
 * @Description:   手写一个反射实现
 * @Author: WDC 
 * @Date: 2020/3/19 10:56
 **/
//@Data
@AllArgsConstructor
//@NoArgsConstructor
//@Accessors(chain = true)
public class User{
    public void eat(){
        System.out.println("eating banana");
    }
    public void look(){
        System.out.println("look eating banana");
    }
}

自定义注解

package com.myspringboot.test;

import javax.lang.model.element.Element;
import java.lang.annotation.*;
/*
 * @Description:    自定义注解
 * @Author: WDC 
 * @Date: 2020/3/19 10:59
 **/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
//@Documented
//@Inherited
public @interface MyAnno {
    String className();
    String methodName();
}

配置文件
```xml
className=com.myspringboot.test.User
methodName = look

反射实现

package com.myspringboot.test;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

/*
 * @Description:    反射实现
 * @Author: WDC 
 * @Date: 2020/3/19 10:58
 **/
@MyAnno(className = "com.myspringboot.test.User",methodName = "eat")
public class ReflectTest{
    public static void main(String[] args) throws Exception{
        //1.获取注解
        //1.1获取该类的字节码对象
        Class<ReflectTest> reflectTestClass = ReflectTest.class;
        //2.获取上边的注解对象
        //其实解释在内存中生成了一个该注解接口的子类实现对象
        MyAnno myAnno = reflectTestClass.getAnnotation(MyAnno.class);

        //3.调用注解对象中定义的抽象方法,获取返回值
        String className = myAnno.className();
        String methodName = myAnno.methodName();
        //加载至内存
        Class cls = Class.forName(className);
        //创建对象
        Object obj = cls.newInstance();
        //获取方法对象
        Method method = cls.getMethod(methodName);
        //执行方法
        method.invoke(obj);
    }
}

你可能感兴趣的:(代码演示)