Skip to content

Instantly share code, notes, and snippets.

@googya
Created April 14, 2011 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save googya/918804 to your computer and use it in GitHub Desktop.
Save googya/918804 to your computer and use it in GitHub Desktop.
package hoodoo.reflection.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Created by IntelliJ IDEA.
* User: Hoodoo
* Date: 11-4-13
* Time: 上午9:49
* To change this template use File | Settings | File Templates.
*/
interface Interface {
void doSomething();
void somethingElse(String args);
}
class RealObject implements Interface {
public void doSomething() {
System.out.println("DoSomething");
}
public void somethingElse(String arg) {
System.out.println("somethingElse " + arg);
}
}
class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("**********proxy*****: " + proxy.getClass() + ".method " + method + ", args : " + args);//这里是代理进行的操作
if (args != null) {
for (Object arg : args) {
System.out.println(" " + arg);
}
}
return method.invoke(proxied, args);//调用被代理类的方法
}
}
public class SimpleDynamicPproxy {
public static void consumer(Interface iafce) {
iafce.doSomething();
iafce.somethingElse("hoodoo");
}
public static void main(String[] args) {
RealObject rb = new RealObject();
// consumer(rb);
Interface proxy = (Interface) Proxy.newProxyInstance(
Interface.class.getClassLoader(),
new Class[]{Interface.class},
new DynamicProxyHandler(rb)
);
consumer(proxy);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment