您需要了解 Java 反射。Java 反射可以在运行时检查类、接口、字段和方法,而无需在编译时知道类、方法等的名称。也可以使用反射实例化新对象、调用方法和获取/设置字段值。下面是一个简单的例子。
package com.example;
public class Emplyoee {
private String name;
public Emplyoee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String args[]) {
String className = "com.example.Emplyoee";
try {
//finds class, casts Emplyoee class
Class<Emplyoee> klass = ((Class<Emplyoee>) Class.forName(className ));
//instantiate new objects,notice Emplyoee class
Emplyoee theNewObject = klass.newInstance();
//set value
theNewObject.setName("john");
//calls "name" by getter method,and prints "john"
System.out.println(theNewObject.getName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Spring容器会通过“forName”方法找到“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”类,并实例化“PropertyPlaceholderConfigurer”类。