动态代理主要实现类为:InvocationHandler,具体代码如下:
proxyTest.java
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class proxyTest {
public static void main(String[] args) { RealSubject mRealSubject = new RealSubject(); InvocationHandler mInvocationHandler = new DynamicProxy(mRealSubject); Subject subject = (Subject)Proxy.newProxyInstance(mInvocationHandler.getClass().getClassLoader(),mRealSubject.getClass().getInterfaces(),mInvocationHandler); System.out.println(subject.getClass().getName()); subject.rent(); subject.hello("Lin"); }
}
|
Subject.java
1 2 3 4 5 6
| public interface Subject {
public void rent();
public void hello(String str); }
|
RealSubject.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class RealSubject implements Subject {
@Override public void rent() { System.out.println("I want to rent my house"); }
@Override public void hello(String str) { System.out.println("hello: " + str); }
}
|
DynamicProxy.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| public class DynamicProxy implements InvocationHandler {
private Object subject; public DynamicProxy(Object object){ subject = object; } @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { System.out.println("before rent house"); System.out.println("Method:" + arg1); arg1.invoke(subject, arg2); System.out.println("after rent house"); return null; }
}
|