}
else
{
obj = method.invoke(sub,args);
}
return obj;
}
}
);
su.fun();
}
}
3.在InvocationHandler实现类内部创建一个bind方法,用来返回代理类实例:
[java]
class InvocationHandlerImpl implements InvocationHandler
{
private Object target = null;
public Object bind(Object target)
{
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method,Object[] args) throws Throwable
{
Object obj = null;
if(method.getName().equals("fun"))
{
before();
obj = method.invoke(target,args);
after();
}
else
{
obj = method.invoke(target,args);
}
return obj;
//return null;
}
private void before()
{
System.out.println("before...");
}
private void after()
{
System.out.println("after...");
}
}
class Main
{
public static void main(String[] args)
{
InvocationHandlerImpl proxy = new InvocationHandlerImpl();
Subject sub = (Subject)proxy.bind(new SubjectImpl());
sub.fun();
}
}
class InvocationHandlerImpl implements InvocationHandler
{
private Object target = null;
public Object bind(Object target)
{
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),this);
}
public Object invoke(Object proxy, Method method,Object[] args) throws Throwable
{
Object obj = null;
if(method.getName().equals("fun"))
{
before();
obj = method.invoke(target,args);
after();
}
else
{
obj = method.invoke(target,args);
}
return obj;
//return null;
}
private void before()
{
System.out.println("before...");
}
private void after()
{
System.out.println("after...");
}
}
class Main
{
public static void main(String[] args)
{
InvocationHandlerImpl proxy = new InvocationHandlerImpl();
Subject sub = (Subject)proxy.bind(new SubjectImpl());
sub.fun();
}
}