反射和注解的等价置换

2021/12/15 23:40:54

本文主要是介绍反射和注解的等价置换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

实现配置式加载某一个类

src/cn.itcast.domain

package cn.itcast.domain;

public class Student {

    public void sleep(){
        System.out.println("开始午休。。。。");
    }
}

反射的写法

src/pro.properties

className = cn.itcast.domain.Student
methodName = sleep

src/ReflectTest

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

public class ReflectTest {
    public static void main(String[] args) throws Exception {
        Class stuClass = Class.forName(getValue("className"));
        Method m = stuClass.getMethod(getValue("methodName"));
        m.invoke(stuClass.getConstructor().newInstance());
    }

    public static String getValue(String key) throws Exception {
    	// Properties集合是一个唯一和IO流相结合的集合
        Properties pro = new Properties();
        // 创建一个文件对象,读取文件到内存
        FileReader in = new FileReader("src/pro.properties");
        // 将文件对象载入集合中
        pro.load(in);
        in.close();
        return  pro.getProperty(key);
    }

}

注解的写法

src/cn.itcast.annotaion.customannotation

package cn.itcast.annotaion.customannotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String className();
    String methodName();
}
import cn.itcast.annotaion.customannotation.MyAnnotation;
import java.lang.reflect.Method;

@MyAnnotation(className = "cn.itcast.domain.Student",methodName = "sleep")
public class AnnotationTest {
    public static void main(String[] args) throws Exception {
        // 获取该类的字节码文件对象
        Class<AnnotationTest> cls = AnnotationTest.class;
        // 返回一个注解实现的实例对象
        MyAnnotation an = cls.getAnnotation(MyAnnotation.class);
        String className = an.className();
        String methodName = an.methodName();
        // 通过反射获取Student的class对象
        Class stuClass = Class.forName(className);
        // 获得一个方法对象
        Method m = stuClass.getMethod(methodName);
        // 获取Student的一个实例对象
        Object obj = stuClass.getConstructor().newInstance();
        m.invoke(obj);
    }
}


这篇关于反射和注解的等价置换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程