package reflect;
public class Person {
public void sayHello() {
System.out.println("HelloJava");
}
public void sayName() {
System.out.println("大家好");
}
public void sayAge(int age) {
System.out.println("我的年齡是:"+age+"歲了...");
}
public void say(String name,int age) {
System.out.println("我叫"+name+",我今年"+age+"歲了。");
}
private void domose() {
System.out.println("我是Preson類的私有方法...");
}
}
調用person類中無參方法
package reflect;
import java.lang.reflect.Method;
/**
* 通過反射機制調用某個類的某個方法
*/
public class ReflectDemo1 {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("reflect.Person");
//接收的是一個Person的實例
Object o =cls.newInstance();
/*
* 通過該Class實例可以獲取其表示的類的相關方法
* 獲取Person的sayHello方法
*
*/
Method method =cls.getDeclaredMethod("sayHello", null);
method.invoke(o, null);
}
}
調用person類中有參方法
package reflect;
import java.lang.reflect.Method;
/**反射調用有參方法
*
*/
public class ReflectDemo3 {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("reflect.Person");
Object o =cls.newInstance();
Method method=cls.getDeclaredMethod("sayAge",new Class[] {int.class});
method.invoke(o, new Object[] {20});
Method method1=cls.getDeclaredMethod("say",new Class[] {String.class,int.class});
method1.invoke(o,new Object[] {"zhangsan",18});
}
}
調用Person類中的私有方法
package reflect;
import java.lang.reflect.Method;
//反射機制調用私有方法
public class ReflectDemo4 {
public static void main(String[] args) throws Exception {
Class cls = Class.forName("reflect.Person");
Object o =cls.newInstance();
Method method=cls.getDeclaredMethod("domose",null);
//強制要求訪問該方法 setAccessible(true);
method.setAccessible(true);
method.invoke(o, null);
}
}
