package test;
import java.lang.reflect.Constructor;
public class Demo {
public static void main(String[] args) {
try {
//3种获取Clazz的方法
Class clazz2 = Class.forName("test.Demo");
Class clazz = Demo.class;
Demo d = new Demo();
Class clazz3 = d.getClass();
//得到默认的构造函数
Constructor constructor = clazz3.getConstructor();
//创建实例
Demo demo = (Demo) constructor.newInstance();
//调用方法
demo.sayHello();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sayHello(){
System.out.println("hello world");
}
}
|