使用JDK动态代理时,有时需要获取原始对象,那怎么通过代理对象获取原始对象呢?
接口 public interface Person { void doWork(); } 实现类 public class PersonImpl implements Person { public void doWork() { System.out.println("testssttt"); } } 代理类 public class PersonProxy implements InvocationHandler { private Person target; public Object getInstance(Person person){ this.target = person; return Proxy.newProxyInstance(person.getClass().getClassLoader(),person.getClass().getInterfaces(),this); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(target,null); return null; } }测试方法:
/** * 从代理对象中获取原始对象 * @throws Exception */ @Test public void testProxy() throws Exception { Person person = (Person) new PersonProxy().getInstance(new PersonImpl()); // person.doWork(); System.out.println(person.getClass()); System.out.println(getTarget(person)); } public Object getTarget(Object proxy) throws Exception { Field field = proxy.getClass().getSuperclass().getDeclaredField("h"); field.setAccessible(true); //获取指定对象中此字段的值 PersonProxy personProxy = (PersonProxy) field.get(proxy); //获取Proxy对象中的此字段的值 Field person = personProxy.getClass().getDeclaredField("target"); person.setAccessible(true); return person.get(personProxy); }测试结果如图,成功获取原始对象
