1.创建Student类
public class Student {
public String name;
private Integer age;
private String sex;
public Student() {
System.out.println("构造器被调用");
}
public Student(String name, Integer age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public void eat(){
System.out.println("吃饭");
}
}
2.配置文件
pro.properties
className=com.hubo.domain.Student
methodName=eat
3.通过类的加载器+配置类+反射
ReflectTest.java
public static void main(String[] args) throws Exception{
// 1 Properties类加载配置文件
Properties properties = new Properties();
// 1.1 类加载器的资源流
InputStream resourceAsStream = ReflectTest.class.getClassLoader().getResourceAsStream("pro.properties");
properties.load(resourceAsStream);
// 得到配置中className和methodName
String className = properties.getProperty("className");
String methodName = properties.getProperty("methodName");
Class<?> aClass = Class.forName(className);
// 创建实例对象
Object o = aClass.newInstance();
// 2.获得所有属性
Field[] declaredFields = aClass.getDeclaredFields();
// 3.获得方法
Method eat = aClass.getMethod(methodName);
eat.invoke(o);
for (Field declaredField : declaredFields) {
String name = declaredField.getName();
String simpleName = declaredField.getType().getSimpleName();
int modifiers = declaredField.getModifiers();
System.out.println(name);
System.out.println(simpleName);
System.out.println(modifiers);
}
}