java實現(xiàn)動態(tài)代理示例分享
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("方法結(jié)束:" + method);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
public interface Animal {
public void hello();
}
動態(tài)代理作為代理模式的一種擴展形式,廣泛應(yīng)用于框架(尤其是基于AOP的框架)的設(shè)計與開發(fā),本文將通過實例來講解Java動態(tài)代理的實現(xiàn)過程。
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();
}
}
相關(guān)文章
Spring Boot利用Thymeleaf發(fā)送Email的方法教程
spring Boot默認就是使用thymeleaf模板引擎的,下面這篇文章主要給大家介紹了關(guān)于在Spring Boot中利用Thymeleaf發(fā)送Email的方法教程,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-08-08
詳解如何使用IntelliJ IDEA新建一個Servlet項目
這篇文章主要介紹了詳解如何使用IntelliJ IDEA新建一個Servlet項目,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
java.lang.Long cannot be cast to ja
本文主要介紹了java.lang.Long cannot be cast to java.lang.Integer數(shù)據(jù)類型轉(zhuǎn)換異常解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07
Java中利用POI優(yōu)雅的導(dǎo)出Excel文件詳解
這篇文章主要給大家介紹了關(guān)于Java中如何利用POI優(yōu)雅的導(dǎo)出Excel文件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Java具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-05-05

