Linux教程網
Java動態代理簡單實現:
- package com.dynamic.proxy;
-
- public class ProxyDemo {
-
- public static void main(String[] args) throws SecurityException, NoSuchMethodException {
-
- LogHandler logHandler = new LogHandler();
-
- IHello hello = (IHello)logHandler.bind(new HelloImp());
-
- hello.toHello("cross");
- hello.toHello1("cross");
-
- }
- }
- package com.dynamic.proxy;
-
- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
-
- public class LogHandler implements InvocationHandler {
-
- private Object deledate;
-
- public Object bind(Object deledate){
- this.deledate = deledate;
- Object proxy = Proxy.newProxyInstance(deledate.getClass().getClassLoader(), deledate.getClass().getInterfaces(), this);
- return proxy;
- }
-
- public Object invoke(Object proxy, Method method, Object[] obj)
- throws Throwable {
-
- doBefore();
-
- Object result = method.invoke(deledate, obj);
-
- doAfter();
-
- return result;
- }
-
- private void doBefore() {
- System.out.println("before....");
- }
-
-
- private void doAfter() {
- System.out.println("after....");
- }
-
- }
- package com.dynamic.proxy;
-
- public interface IHello {
- public void toHello(String name);
- public void toHello1(String name);
- }
- package com.dynamic.proxy;
-
- public class HelloImp implements IHello {
-
- public void toHello(String name) {
- System.out.println("method hello:" + name);
- }
- public void toHello1(String name) {
- System.out.println("method hello1:" + name);
- }
-
- }
Copyright ©
Linux教程網 All Rights Reserved