public class Manager {
private String name = "xq";
public void getName() {
System.out.println(name);
}
public void setName(String name, int a) {
this.name = name + a;
}
/**
* 测试
*
* @param args
*/
public static void main(String[] args) {
try {
test1();
System.out.println("--------------------------------");
test2();
System.out.println("--------------------------------");
test3();
System.out.println("--------------------------------");
} catch (Exception e) {
System.out.println(e);
}
}
/**
* 通过 [类.class] 获得Class对象
*
* @throws Exception
*/
private static void test1() throws Exception {
Class clazz = Manager.class;
Object object = clazz.newInstance();
handle(clazz, object, 1);
}
/**
* 通过 [实例名.getClass()] 获得Class对象
*
* @throws Exception
*/
private static void test2() throws Exception {
Manager object = new Manager();
Class clazz = object.getClass();
handle(clazz, object, 2);
}
/**
* 通过 [Class.forName(全路径)] 获得Class对象
*
* @throws Exception
*/
private static void test3() throws Exception {
Class clazz = Class.forName("Manager");
Object object = clazz.newInstance();
handle(clazz, object, 3);
}
private static void handle(Class clazz, Object object, int i) throws Exception {
Method getName = clazz.getDeclaredMethod("getName", new Class[]{});
Method setName = clazz.getDeclaredMethod("setName", new Class[]{String.class, int.class});
getName.invoke(object); // 获取默认值
setName.invoke(object, "Setting new ", i); // 设置
getName.invoke(object); // 获取最新
}
}
反射获取类的实例Class.forName
最新推荐文章于 2022-06-22 17:15:32 发布