當前位置:科普知識站>IT科技>

aspect|java

IT科技 閱讀(2.44W)

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

aspect java是一個面向切面的框架,它擴展了Java語言。AspectJ定義了AOP語法所以它有一個專門的編譯器用來生成遵守Java字節編碼規範的Class檔案

首先是幾個概念:

aspect(層面)

pointcut(切入點)

advice(建議)

weave(織入)

LTW(加載期織入 load time weave)

按照aspectj的語法規則,一個aspect就是很多pointcut和advice的集合,也就是一個*.aj的檔案。

一個pointcut就是對target class的切入點定義,類似Java class定義中的field。

一個advice就是對target class的行爲改變,類似Java class中的method。

weave就是aspectj runtime庫把aspect織入到target class的行爲。

LTW就是指執行期間動態織入aspect的行爲,它是相對靜態織入行爲(包括對源檔案、二進制檔案的修改)。

一般來講,從執行速度上來說,靜態織入比動態織入要快些。因爲LTW需要使用aspectj本身的classloader,它的效率要低於jdk的classloader,因此當需要load的class非常多時,就會很慢的。

aspect java

舉個例子來說明aspectj的使用:

scenario: Example工程需要使用一個類Line存在於第三方庫Line.jar中,但是Line本身沒有實現Serializable接口,並且其toString方法輸出也不完善。因此這兩點都需要修改。

Line的實現:

package bean;public class Line {undefinedprotected int x1 = 0;protectedint x2 = 0;public intgetX1(){undefinedreturn x1;}public intgetX2(){undefinedreturn x2;}public voidsetLength(int newX, int newY){undefinedsetX1(newX);setX2(newY);}public voidsetX1(int newX) {undefinedx1 = newX;}public voidsetX2(int newY) {undefinedx2 = newY;}publicString toString(){undefinedreturn "(" + getX1() + ", " + getX2() + ")" ;}}Main entry :public class MyExample {undefinedprivate Line line = null;public MyExample() {undefinedline = new Line();System.err.println("Lineimplement serializable interface : "+(line instanceof Serializable));}public void showMe() {undefinedSystem.out.println("Show allabout me ...");System.out.println(line.toString());}public static void main(String[] args) {undefinedMyExample demo = newMyExample();// i want to change the actionof show me, but i cannot get line source.// so i will trying load-timeweavingdemo.showMe();}}output :Line implement serializable interface : trueShow all about me ...(0, 0)