class proxy
3550 단어 java proxy
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
class MyInvocationHandler implements InvocationHandler{
private Object source ;
public MyInvocationHandler(Object source){
this.source = source ;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// System.out.println(proxy);// StackOverflowError course by recurse
System.out.println(proxy.getClass());//proxy-class,not source-class
if(null!=args){
for(Object param : args){
System.out.println(param);//method-input-param
}
}
System.out.println("u can do special things before method-execute");
Object obj = method.invoke(source, args);//Point:source,not proxy. proxy's meaning?
System.out.println("u can do special things after method-execute");
return obj ;
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ClassProxyTest {
/**
* @param args
*/
public static void main(String[] args) {
PojoWithoutInterface pojo = new PojoWithoutInterface();
pojo.setName(1111);
Object pojoProxy = ClassProxyTest.getProxyInstance(pojo);
// pojo = (PojoWithoutInterface) pojoProxy ;// class cast exception
System.out.println(pojoProxy);
Object pojoProxy1 = ClassProxyTest.getProxyInstance(pojo);// not equals,new instance
System.out.println(pojoProxy.equals(pojoProxy1));//object 's method should be proxy
ClassImplInterface impl = new ClassImplInterface() ;
Object implProxy = ClassProxyTest.getProxyInstance(impl) ;
InterfaceA interA = (InterfaceA) implProxy ;
interA.methodA() ;
}
public static Object getProxyInstance(Object source){
InvocationHandler myInvoHandler = new MyInvocationHandler(source) ;
Object proxy = Proxy.newProxyInstance(source.getClass().getClassLoader(), source.getClass().getInterfaces(), myInvoHandler) ;
Method[] publicMethods = proxy.getClass().getMethods() ;// proxy only have source's interface-method,not all-method
if(null!=publicMethods){
for(Method mthd : publicMethods){
System.out.println(mthd.getName());
}
}
return proxy ;
}
}
class ClassImplInterface implements InterfaceA,InterfaceB{
@Override
public void methodA() {
System.out.println("methodA execute");
}
@Override
public void methodB() {
System.out.println("methodB execute");
}
public void methodC(){//proxy can not execute
System.out.println("self-method execute");
}
}
public class PojoWithoutInterface {
private int name ;
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
}
public interface InterfaceA {
void methodA() ;
}
public interface InterfaceB {
void methodB() ;
}