aspect java

<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)