Learn AspectJ (3)

zhaozj2021-02-16  50

Chapter II Aspectj Language

Quote

In the previous chapter of this series, we briefly explain the sum of AspectJ languages. To understand AspectJ's grammar and semantics, you should read this chapter. This part includes some of the materials described above, but will be more complete and more discussion details. The article will begin with a specific aspect, including a cut point, a type of declaration and two notifications, which will give us some topics discussed.

The anatomy of anast

First give our definition aspects.

1 aspect faulthandler {

2

3 private boolean server.disabled = false;

4

5 private void reportfault () {

6 System.out.Println ("Failure! Please fix it.");

7}

8

9 public static void fixserver (server s) {

10 s.disabled = false;

11}

12

13 PointCut Services (Server S): Target (s) && call (public * * (.));

14

15 Before (Server S): Services (s) {

16 if (s.disabled) throw new disabledexception ();

17}

18

19After (Server S) THROWING (FaultException E): Services (s) {

20 s.disabled = true;

21 reportfault ();

twenty two }

twenty three }

FAULTHANDLER includes a type field declaration (line 3) on Server, two methods (5-7 rows and 9-11 lines), cut points definition (13 lines), two notices (15-17 rows and 19 -22 line). These coverage of basic information that can be included. Generally, aspects include other program entities, different variables, methods, cleavage definitions, types, and notifications (possibly beh, installs). The remainder of the article will discuss these cross-cutting structures one by one.

Pointcuts

Aspectj's cleansing point is defined as a cut point. Clean yourself to capture the connection point collection, for example, the point of interest in the program execution. These connection points can be a method or constructor call or execution, an abnormality processing, a field assignment, and a like. For example, the cut point definition in 13 lines:

PointCut Services (Server S): Target (s) && call (public * * (..))

This cut point is named Services, capturing the connection point during the execution of the server when the public method of the Server object is called. It also allows anyone who uses the Services cleavage point to access the Server object called by those methods. The idea of ​​this cutting point behind the faulthandler means that the behavior of error handling must be triggered by the call of public methods. For example, Server may not handle requests because certain errors cannot be processed. Therefore, the call to those methods is an event of interest in this aspect. When these events occur, the corresponding errors will happen.

The part of the event occurs, is exposed by the parameters of the cut point. In this example, it means an object of the Server type. This parameter is used on the right side of the cut point declaration to indicate which event is related to the cleaning point. In the example, the Services cleaning point includes two parts, which is a connection point that captures those operations that are target objects (S)) (Call (..)) combined with the connection point of the Target (S)) (Call (..)). &&, intended to be logical and And). The call connection point (Calls) is described by the method, in this case, several wildcard expressions are used. The position of the return type is (*), where the location of the method name is (*) and in the parameter list position is (..); only one specific message is, it is public. Clear points capture a large number of connection points in the program. But they only capture several connection points. These types of connection represent some important concepts in the Java language. Here is an incomplete list for these concepts: method call, method execution, exception processing, instantiation, constructive sub-execution, and field access. Each connection point is captured by a specific cut point, you will learn them in other parts of this article.

ADVICE

A notification consists of a cutpoint and a notification code that defines the logic running at the connection point captured by the cut point. For example, the code if (s.disabled) throw new disableDexception () in the notice of the 15-17 row; is executed when the instance of the Server calls. Another notification defined by the 19-22 line is performed at the same cutout point (SERVICES).

{

s.disabled = true;

Reportfault ();

}

At that time, the second notice was only performed when the program throws FAULTEXCEPTION. There are three categories of After notifications: the method is ended based on the normal end, and the method is ended and the method ends in any way.

Join Points and Pointcuts

Consider the following Java class

Class point {

Private int x, y;

Point (int x, int y) {this.x = x; THIS.Y = Y;}

Void setx (int x) {this.x = x;}

Void setY {this.y = y;

INT getX () {returnix x;}

INT gety () {return y;}

}

In order to understand AspectJ's connection point and cut point concept, let's review some of the basic principles of the following Java languages. Considering the method in the class Point Declaration Void Setx (INT X) {this.x = x;} This program segment Description When the Point class instance calls the form of set {TEX, the program executes method body {this.x = x;}. Similarly, the structure of the class indicates that if the POINT class uses two integer parameters, {this.x = x; this.y = y;} will be executed. Summary with a sentence is: When some things happen, there are some things to be executed. In an object-oriented program, some kinds of "what happen" is determined by the language itself. We call these connection points for Java. The connection point has some like method calls, method execution, object instantiation, constructor execution, field reference, and exception processing.

And the cut point is to capture the structure of these connection points, for example, the following cutting point

Pointcut setter (): Target (Point) &&

(Call (void setx (int)) ||

Call (Void SetY (int));

Capture each method call to setX (int) or sety (int) on the Point instance. Take a look at another example

Pointcut ohandler (): with (myclass) && handler (IOEXCEPTION); this cleaning point captures each connection point when the exception handling code execution is executed.

Clearance definitions include two parts divided by colon. The left side includes the name of the cut point and the parameters of the cleaning point (eg, the data when the event occurs). The right side includes the cutting point itself.

Example of some cut points

The following clearance is the function of performing a specific method

Execution (Void Point.setx (int))

Use when the method is called

Call (void point.setx (int))

The cut point when the abnormality handle is executed is as follows.

ARRAYOUNDSEXCEPTION

Objects that are currently using Sometype types

this (SomeType)

Sometype type object is the target object

Target (SomeType)

If the connection point is in the Test's non-parameter main function call process

cflow (call (void test.main ())

Subsets can also be used or ("| |") and ("And") and non-("!").

· You can use wildcards. therefore

1. Execution (* * (..))

2. Call (* set (..))

Representative (1) Any method of not considering parameters and return values ​​(2) The method called the SET method for any parameter and the return value.

· Select elements based on the type, for example

1. EXECUTION (int * ())

2. Call (* setY (long))

3. Call (* Point.Sety (int))

4. Call (*. New (int, int))

Representative (1) Return value is any parameterless method for INT type; (2) any return type and parameter is called the sety method called the set of the set method; (3) An arbitrary Point object has an Int type set method call Ignore the return type; (4) For any class of constructor, as long as the structure has two int type parameters.

· How to combine the point, for example

1. Target (Point) && call (int * ())

2. Call (* * (..)) && (will (line) || within (point))

3. WITHIN (*) && execution (*. New (int))

4. ! this (point) && call (int * (..))

Representative (1) Point instance returns any parameterless method call to INT; (2) LINE or POINT definition and any method call generated by the actual example; (3) Arbitrace for arbitrary constructor call; (4) Any return to the type of INT type is called as long as the current execution class instance is not a Point type.

· Choose a method or constructive of a specific modification

1. Call (public * * (..))

2. Execution (! Static * * (..))

3. Execution (public! Static * * (..))

Representative (1) call; (2) execution of any non-static method; (3) Execution of any common non-static method.

• The cut point is also able to handle the interface. For example, a given interface

Interface myinterface {...}

Clear point Call (* MyInterface. * (..)) Capture the method of MyInterface definition and method calls for hypercarriage definitions. Cut point synthesis

Subsets can use operators and (&&), or (||) and non (!). This can use a simple original cleaner to create a cut point for powerful functions. When combining the original cut point cflow and cflowbelow, it may be a bit confused. For example, cflow (p) captures all connection points (including P) (including P), you can use graphical representation

P ---------------------

/

/ Cflow of p

/

So what is Cflow (P) && cflow (q) captured? It captures the connection point in the P and Q processes.

P ---------------------

/

/ Cflow of p

/

/

/

Q ------------- / -------

/ /

/ Cflow of q / cflow (p) && cflow (q)

/ /

Note that P and Q may have no public connection points, but there may be public connection points in their program flow.

What does cflow (p && q) mean? It means the process of connecting points that are captured by P and Q.

P && Q -------------------

/

/ Cflow of (p && q)

/

If P and Q have not captured a common connection point, there is no connection point in the process of (P && Q). The following code shows the above meaning

Public class test {

Public static void main (String [] args) {

Foo ();

}

STATIC void foo () {

GOO ();

}

Static void goo () {

System.out.println ("hi");

}

}

Aspect a {

Pointcut foopc (): Execution (void test.foo ());

Pointcut Goopc (): Execution (Void Test.goo ());

Pointcut PrintPC (): Call (Void (Void Java.io.PrintStream.Println (String));

Before (): cflow (foopc ()) && cflow (goopc ()) &&printpc () {

System.out.println ("Should Occur");

}

Before (): cflow (foopc () && goopc () &&printpc () {

System.out.Println ("Should Not Occur");

}

}

Point parameters

Consider the following code

Pointcut setter ():

Target (Point) && (Call (Void Setx (INT)) || Call (Void Set));

This cut point captures the call of each setx (int) or sety method that targets the Point instance. The cut point is setters and there is no parameters on the left. Empty parameter columns mean that the cleansions do not expose the context information of any connection point. But consider the cut point definition of another version

PointCut Setter (POINT P):

Target (P) && (Call (Void Setx (Int)) || Call (Void Set));

Its function is the same as the description points described above, but the cleaning point here includes a parameter type as a POINT. This means that any notifications using this cut point can access the Point instances in the connection point to capture the connection point. Take a look at another version of the setters cleaner

Pointcut Setter (POINT P, INT NEWVAL): Target (P) && Args (NewVal)

&& (Call (void setx (int)) || Call (Void Sety (int)));

Here is the point to expose a Point object and an int value. At the right side of the cut point defined, we found that the Point object is a target object, and the int value is the parameter of the modified method.

The use of the cut point parameters has a lot of scalability. The most important rule is that all cutpoint parameters must be bound to the connection point captured in each cut point. Therefore, the following example will compile errors.

Pointcut Badpointcut (Point P1, Point P2):

(Target (P1) && Call (Void Setx (int)) ||

(Target (P2) && Call (Void SetY (int));

Because P1 is bound only when the setX calls, the P2 is bound to the sety call, but the cleaning point captures all of these connection points and attempts to bind P1 and P2 simultaneously.

An example: Handeliveness

This example includes two object classes, an exception class, and one aspect. The Handle object is just a non-statically public method for the agent Partner object. Aspects, HandleLiveness, make sure that Partner exists and available before the agent, otherwise an exception is thrown.

Class Handle {

Partner partner = new partner ();

Public void foo () {partner.foo ();

Public void bar (int x) {partner.bar (x);

Public static void main (String [] args) {

Handle h1 = new handle ();

H1.foo ();

H1.bar (2);

}

}

Class partner {

Boolean isalive () {return true;}

Void foo () {system.out.println ("foo");}

Void Bar (int x) {system.out.println ("bar" x);

}

Aspect handeliveness {

Before (Handle Handle): Target (Handle) && call (public * * (..)) {

IF (Handle.Partner == Null ||! Handle.Partner.isAlive ()) {

Throw new deadnerexception ();

}

}

}

Class Deadpartnerexception Extends runtimeException {}

More information

1. Aspectj Installation and Configuration Guide

2. Learn Aspectj with me (1)

If you need to pay, please write a name author and source.

转载请注明原文地址:https://www.9cbs.com/read-26873.html

New Post(0)