一、java中获取java.lang.class对象操作方法
1. 可以利用Class.forName("类的全路径")
2. this.getClass()
3.对象.class
这三种方法获取的结果都是Class对象
二、利用反射执行方法Method
import java.lang.reflect.Method;
public class TestClassLoad {
public static void main(String[] args) throws Exception {
Class<?> clz = Class.forName("A");
Object o = clz.newInstance();
Method m = clz.getMethod("foo", String.class);
for (int i = 0; i < 16; i++) {
m.invoke(o, Integer.toString(i));
}
}
}
上面程序中可以将clz换为this.getClass()来执行获取Method对象,invoke(类对象,方法参数)
三、根据配置文件执行不同的类
public class Factory {
private static Properties props;
static {
System.out.println("静态代码块");
props = new Properties();
try {
props.load(new FileInputStream("./src/main/resources/config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
{
System.out.println("非静态代码块");
}
public static User getUserInstance() throws Exception{
return (User) Class.forName(props.getProperty("user")).newInstance();
}
}
原文:https://www.cnblogs.com/ya-qiang/p/9320526.html