一、代码
package com.sangfor.tree;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface ProxyInterFace {
public void proxyMethod();
class TargetObject implements ProxyInterFace {
public void proxyMethod() {
System.out.println("我被代理了,哈哈!");
class ProxyObject implements InvocationHandler {
public Object targetObject;
public void setTargetObject(Object targetObject) {
this.targetObject = targetObject;
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("代理前 你可以做的事情");
Object object = method.invoke(targetObject, args);
System.out.println("代理后 你可以做的事情");
public static void main(String[] args) {
ProxyInterFace target = new TargetObject();
ProxyObject proxy = new ProxyObject();
proxy.setTargetObject(target);
InvocationHandler handler = proxy;
Object newProxyObject = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler);
((ProxyInterFace)newProxyObject).proxyMethod();
二、结果