大家都知道java类中被声明private的方法和private的属性,在其他类中是无法访问的,但是我们可以利用java给我提供的反射机制就可以实现对私有方法和私有属性的访问。废话不多说,直接上代码
package reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/*
* 该类主要练习使用java的反射机制调用其他类的
* private方法和变量;
*/
public class MethodTest
{
public static void main(String[] args) throws Exception
{
Class<?> classType = People.class;
People p1 =(People) classType.newInstance();
// 获取指定的方法,调用People类的私有方法;
Method method = classType.getDeclaredMethod("sayHello",
new Class[] { String.class });
method.setAccessible(true);//压制java的访问修饰符;
method.invoke(p1, new Object[]{"Mr zhou"});
//获取People类的私有属性;
Field field = classType.getDeclaredField("age");
field.setAccessible(true);
field.set(p1, 12);
System.out.println(field.get(p1));
}
}
class People
{
private int age;
private String name;
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
private void sayHello(String str)
{
System.out.println("Hello: " + str);
}
}
People类中声明的sayHello方法和age、name都是私有的,但是,我们通过反射机制就可以调用该方法和使用其属性。