/*定义一个猫类用反射输出他打哈欠的方法
* */
public class 反射打哈欠 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
Class clazz = Class.forName("com.heima.test.Cat");
Method m = clazz.getMethod("show");//获取方法
m.invoke(clazz.newInstance());
}
}
class Cat{
public void show(){
System.out.println("猫打哈欠!");
}
} |
|