package com.lousen.test_2;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 反射
* 通过字符串来创建同名类的对象
* */
public class FanShe {
public static void main(String[] args){
try {//根据字符串创建对象,用java反射中的Class.forName();通过调用静态方法forName或得类名对应的Class对象。
String clazzName = "School"; //School类要存在
Class clazz = Class.forName("com.lousen.test_2."+clazzName);
Object obj = clazz.newInstance();
//调用类中方法用Method——其中getMethods()方法获取类中所有方法,带参数的或得指定的方法。
Method method = clazz.getMethod("recruitStudent");
method.invoke(obj);
//调用类中属性用Field,当属性是私有的时候需要f.setAccessible(true);
Field f = clazz.getDeclaredField("address");
f.setAccessible(true);
Object o = f.get(obj);
System.out.print(o.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}