见附件,可运行,本人亲写亲测。
package com.test.proxy;
public interface ProxyInterface {
public void realMethod();
}
package com.test.proxy;
public class ProxyImpl implements ProxyInterface {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void realMethod(){
System.out.println("method in real Impl.");
}
}
package com.test.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class proxyImplHandler implements InvocationHandler{
public ProxyInterface impl;
proxyImplHandler(ProxyInterface impl){
this.impl=impl;
}
@Override
public Object invoke(Object obj, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("Before realmethod invoke........");
method.invoke(this.impl, args);
System.out.println("after realmethod invoke........");
return null;
}
}
package com.test.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ProxyInterface imp =new ProxyImpl();
InvocationHandler handler = new proxyImplHandler(imp);
ProxyInterface o = (ProxyInterface)Proxy.newProxyInstance(
imp.getClass().getClassLoader(),
imp.getClass().getInterfaces(),
handler);
o.realMethod();
}
}
package com.test.proxy;
public interface ProxyInterface {
public void realMethod();
}
package com.test.proxy;
public class ProxyImpl implements ProxyInterface {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void realMethod(){
System.out.println("method in real Impl.");
}
}
package com.test.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class proxyImplHandler implements InvocationHandler{
public ProxyInterface impl;
proxyImplHandler(ProxyInterface impl){
this.impl=impl;
}
@Override
public Object invoke(Object obj, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("Before realmethod invoke........");
method.invoke(this.impl, args);
System.out.println("after realmethod invoke........");
return null;
}
}
package com.test.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ProxyInterface imp =new ProxyImpl();
InvocationHandler handler = new proxyImplHandler(imp);
ProxyInterface o = (ProxyInterface)Proxy.newProxyInstance(
imp.getClass().getClassLoader(),
imp.getClass().getInterfaces(),
handler);
o.realMethod();
}
}