java实现动态代理示例分享
import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;
public class loghandler implements invocationhandler {
private object delegate;
public object bind(object delegate) {
this.delegate = delegate;
return proxy.newproxyinstance(delegate.getclass().getclassloader(),
delegate.getclass().getinterfaces(), this);
}
@override
public object invoke(object proxy, method method, object[] args)
throws throwable {
object result = null;
try {
system.out.println("方法开始:" + method);
result = method.invoke(delegate, args);
system.out.println("方法结束:" + method);
} catch (exception e) {
e.printstacktrace();
}
return result;
}
}
public interface animal {
public void hello();
}
动态代理作为代理模式的一种扩展形式,广泛应用于框架(尤其是基于aop的框架)的设计与开发,本文将通过实例来讲解java动态代理的实现过程。
public class monkey implements animal {
@override
public void hello() {
// todo auto-generated method stub
system.out.println("hello");
}
}
public class main {
public static void main(string[] args) {
loghandler loghandler = new loghandler();
animal animal = (animal) loghandler.bind(new monkey());
animal.hello();
}
}
下一篇: python中如何使用朴素贝叶斯算法