回忆(六):反射访问私有方法和公有方法
package reflex;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectDemo06_getMethods_invoke_parameter_private {
/*
*
* 前面有过构造方法;
* 成员变量;
* 最后一个:
* 成员方法; 同样对于私有方法和公有方法
*
* 获取所有方法:
* getMethods
* getDeclaredMethods
*
* 获取单个方法:
* getMethod
* getDeclaredMethod
*
* 暴力访问:
* method.setAccessible(true);
*/
public static void main(String[] args) throws Exception{
// 获取字节码文件对象
Class c = Class.forName("reflex.Person");
// 获取所有的方法:此方法比较特殊,连父亲的方法也拿了
// 其中包括Object的方法,例如:notify 和 notifyAll
Method[] methods = c.getMethods();
for(Method method : methods) {
System.out.println(method);
}
/*
* Person p = new Person();
* p.show();
* 首先要有对象
*/
Constructor con = c.getConstructor();
Object obj = con.newInstance();
// 获取单个方法并使用
// 获得show方法
// 前面是名称,后面是方法的参数
// public Method getMethod(String name, Class<?>... parameterTypes)
Method m1 = c.getMethod("show");
// 错误:obj.m1();
// invoke:引援
// public Object invoke(Object obj, Object... args)
// 对带有指定参数的指定对象调用由此 Method 对象表示的底层方法。
// 返回值是用Object接收的;
// 第一个参数是指对象是谁
// 第二个参数表示调用该方法的实际采参数(方法的参数)
// 因为我们的show方法没有返回值所以不需要接收。
// 也因为我们的show方法没有参数,所以后面没有args
m1.invoke(obj); //打印输出:show
// 调用Person中的public void method(String s)
Method m2 = c.getMethod("method", String.class);
m2.invoke(obj, "hello");
// 调用Person中的public String getString(String s, int i)
Method m3 = c.getMethod("getString", String.class, int.class);
Object string = m3.invoke(obj, "hello", 1);
System.out.println(string);
Method m4 = c.getDeclaredMethod("function");
m4.setAccessible(true);
m4.invoke(obj);
}
}
其中的person:
package reflex;
public class Person {
// 成员变量
private String name;
int age;
public String address;
// 构造方法
public Person() {
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
private Person(String name) {
this.name = name;
}
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// 成员方法
public void show() {
System.out.println("show");
}
public void method(String s) {
System.out.println("method" + s);
}
public String getString(String s, int i) {
return s + "---" + i;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", address=" + address + "]";
}
private void function() {
System.out.println("function");
}
}