通过反射访问私有方法

 1 package com.dy.xidian;
 2 
 3 import java.lang.reflect.InvocationTargetException;
 4 import java.lang.reflect.Method;
 5 
 6 class A {
 7     private void a() {
 8         System.out.println("This is a function");
 9     }
10 }
11 public class TestReflect {
12     public static void main(String[] args) throws NoSuchMethodException,
13             SecurityException, IllegalAccessException,
14             IllegalArgumentException, InvocationTargetException {
15         A a = new A();
16         Method g = a.getClass().getDeclaredMethod("a");
17         g.setAccessible(true);
18         g.invoke(a);
19     }
20 }

通过反射机制可以访问A中的私有方法。

posted @ 2016-05-07 14:12  被罚站的树  阅读(146)  评论(0编辑  收藏  举报