方法一:使用配置文件和反射实现
定义配置文件如下,调用 Student 类中的 sleep() 方法:
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws Exception {
//1、加载配置文件
//创建Properties对象
Properties pro = new Properties();
//加载配置文件,转换为一个集合
//获取class目录下的配置文件
ClassLoader classLoader = TestReflect.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("pro.properties");
pro.load(is);
//2、获取配置文件中定义的数据
String className = pro.getProperty("className");
String methodName = pro.getProperty("methodName");
//3、加载该类进入内存
Class cls = Class.forName(className);
//4、创建对象
Object obj = cls.newInstance();
//5、获取方法对象
Method method = cls.getMethod(methodName);
//6、执行方法
method.invoke(obj);
}
}
方法二:使用注解实现
定义注解,描述需要执行的类名和方法名:
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 Pro {
String className();
String methodName();
}
实现类,添加自定义注解,输入类名和方法名:
@Pro(className = "com.testcode.javase.test_7_2.Person",methodName = "eat")
public class Test01 {
public static void main(String[] args) throws Exception{
//1、解析注释
//获取该类的字节码文件对象
Class<TestReflect02> testReflect02Class = TestReflect02.class;
//2、获取上边的注解对象
//其实就是在内存中生成了一个该注解接口得子类实现对象
Pro an = testReflect02Class.getAnnotation(Pro.class);
//3、调用注解对象中定义的抽象方法,获取返回值
String className = an.className();
String methodName = an.methodName();
System.out.println(className);
System.out.println(methodName);
}
}