java反射获取类实例并调用私有方法

来源:互联网 发布:sql误修改数据恢复 编辑:程序博客网 时间:2024/05/21 12:04
public class TestReflect {//测试类public void mPublic() {//访问权限最大System.out.println("public run");}protected void mProtected() {//同包下才能访问(实验对象)System.out.println("protected run");}private void mPrivate() {//只有本类中才能访问(实验对象)System.out.println("private run");}}

public static void main(String[] args) throws Exception {Class<?> class1 = null;// 反射获取类实例,用的最多的就是jdbc获取驱动的时候就是用Class.forName("xxx");// 一般采用这种形式class1 = Class.forName("com.xxx.TestReflect");// class1 = new TestReflect().getClass();// class1 = TestReflect.class;// 类实例化,到这里就可以访问TestReflect类的public属性的成员方法和成员变量了TestReflect tr = (TestReflect) class1.newInstance();// 通过java.lang.Class类得到一个Method对象// api中java.lang.Class.getDeclaredMethod方法介绍// 返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法。    Method method = class1.getDeclaredMethod("mPrivate");    Method method1 = class1.getDeclaredMethod("mProtected");        //将此对象的 accessible 标志设置为指示的布尔值。//值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。//值为 false 则指示反射的对象应该实施 Java 语言访问检查。    method.setAccessible(true);     method1.setAccessible(true);        // 调用该方法    method.invoke(tr);    method1.invoke(tr);}


推荐一位大牛写的反射。。。分分钟秒杀我这种小菜鸟:http://www.cnblogs.com/lzq198754/p/5780331.html