我想处理从 Circle.getArea()
方法使用aspectj。
形状.java
package Shapes;
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getPerimeter(){
return 2 * Math.PI * this.radius;
}
public double getArea(){
return Math.PI * this.radius * this.radius;
}
}
矩形.java
package Shapes;
public class Rectangle {
private double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getPerimeter() {
return 2 * (this.width + this.height);
}
public double getArea() {
return this.width * this.height;
}
}
圆圈.java
package Shapes;
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getPerimeter() {
return 2 * Math.PI * this.radius;
}
public double getArea() {
throw new RuntimeException("Oops, I don't know how to calculate this :(");
}
}
主.java
package Shapes;
public class Main {
public static void main(String[] args) {
try {
Shape s;
s = (Shape) new Rectangle(2, 10);
System.out.println("The area of " + s + " is " + s.getArea());
s = (Shape) new Rectangle(-2, 10);
System.out.println("The perimeter of " + s +" is " + s.getPerimeter());
s = (Shape) new Circle(-2);
System.out.println("The perimeter of " + s +" is " + s.getPerimeter());
s = (Shape) new Circle(2);
System.out.println("The area of " + s + " is " + s.getArea());
}
catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
解析.aj
package Shapes;
privileged public aspect Resolve {
declare parents: Rectangle implements Shape;
declare parents: Circle implements Shape;
public String Rectangle.getName(){
return "Rectangle";
}
public String Circle.getName(){
return "Circle";
}
public String Rectangle.toString(){
return this.getName()+"("+this.width+","+this.height+")";
}
public String Circle.toString(){
return this.getName()+"("+this.radius+")";
}
after() throwing(RuntimeException e) : execution(* Circle.*()){
handleException();
}
protected void handleException()
{
System.out.println("Error detected");
}
}
电流输出为:
The area of Rectangle(2.0,10.0) is 20.0
The perimeter of Rectangle(-2.0,10.0) is 16.0
The perimeter of Circle(-2.0) is -12.566370614359172
Error detected
Error: Oops, I don't know how to calculate this :(
我想避免打印“error:oops,我不知道如何计算:(”,我需要得到圆对象的真实面积。但是,我不能更改任何.java文件。所有更改都应使用resolve.aj文件。
1条答案
按热度按时间ruoxqz4g1#
你需要使用
around
建议而不是后面的建议:代码输出:
为什么我们要用周围的建议而不是后面的建议?
非常非正式地说
around
advice截获给定的joinpoint,并可以在joinpoint之前、之后和之后注入新行为,而不是该joinpoint。这个proceed
是允许around
建议继续执行joinpoint
.从aspectj支持的通知类型(即。,
before
,after
,和around
),的around
通知是唯一允许返回值和/或使用proceed
. 这就使得around
建议多次执行同一连接点,或根本不执行。此外,您甚至可以使用不同的上下文执行截获的joinpoint(例如,更改方法参数的值)。有关建议和继续如何工作的更多信息可以在此so线程上找到。
我们的
around
通知将截获类中所有方法的执行连接点Circle
,并将相应地处理这些方法引发的异常。