/**
*接口类
*/
package com.mzh.common;
public interface IHelloWorld {
public void sayHello();
}
/**
* 实现类
*/
package com.mzh.common;
public class HelloWorldImpl implements IHelloWorld {
public void sayHello() {
System.out.println("Hello,World!");
}
}
/**
* 代理类
*/
package com.mzh.common;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class HelloWorldProxy implements InvocationHandler {
private IHelloWorld helloWorld;
public HelloWorldProxy(IHelloWorld helloWorld){
this.helloWorld=helloWorld;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("我来代理。");
return method.invoke(this.helloWorld, args);
}
public static Object getInstence(IHelloWorld target){
Class targetClass = target.getClass();
ClassLoader loader = targetClass.getClassLoader();
Class[] inters = targetClass.getInterfaces();
HelloWorldProxy handler = new HelloWorldProxy(target);
return Proxy.newProxyInstance(loader,inters, handler);
}
}
/*
* 测试类
*/
package com.mzh.common;
public class TestProxy {
public static void main(String[] args) {
// TODO Auto-generated method stub
IHelloWorld helloWorld = new HelloWorldImpl();
IHelloWorld helloProxy = (IHelloWorld)HelloWorldProxy.getInstence(helloWorld);
helloProxy.sayHello();
}
}
|