packageorg.example.entity;importjava.util.Optional;publicclassTriangle{privatefloat[]sides;publicTriangle(float[]sides){this.sides=sides;}// To validate if the triangle is a valid one.
publicOptional<String>validateTheTriangle(){if(sides.length!=3)returnOptional.of("Sides number must be 3.");for(floatside:sides){if(side<=0)returnOptional.of("Sides must be larger than 0.");if(sides[0]+sides[1]<=sides[2]||sides[1]+sides[2]<=sides[0]||sides[0]+sides[2]<=sides[1])returnOptional.of("The sides cannot form a triangle.");}returnOptional.empty();}}
packageorg.example.aop;importjava.util.Optional;importjava.util.logging.Logger;importorg.aspectj.lang.JoinPoint;importorg.aspectj.lang.annotation.After;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Pointcut;importorg.example.entity.Triangle;@AspectpublicclassTriangleAspect{privatefinalLoggerlogger=Logger.getLogger(TriangleAspect.class.getName());@Pointcut("execution(org.example.entity.*.new(..))")publicvoidtriangleJointPoint(){}@After("triangleJointPoint()")publicvoidafterCreatingTriangleAdvice(JoinPointjoinPoint){Triangleinstance=(Triangle)joinPoint.getTarget();Optional<String>op=instance.validateTheTriangle();if(op.isPresent()){logger.info("Invalid due to: "+op.get());}else{logger.info("Valid!");}}}
importorg.example.entity.Triangle;importorg.junit.jupiter.api.Test;classRawTest{@TestvoidtestValidTriangle(){Triangletriangle=newTriangle(newfloat[]{12F,13F,14F});}// Output:
// Nov 28, 2022 4:50:48 PM org.example.aop.TriangleAspect afterCreatingTriangleAdvice
// INFO: Valid!
@TestvoidtestInValidTriangle(){Triangletriangle=newTriangle(newfloat[]{50F,13F,14F});}// Output:
// Nov 28, 2022 4:48:21 PM org.example.aop.TriangleAspect afterCreatingTriangleAdvice
// INFO: Invalid due to: The sides cannot form a triangle.
}
可以看到在呼叫 new 的時候,我們成功的執行了在 Triangle 裡面的檢查 (validateTheTriangle),這樣一來就可以利用 AOP 的方式來判斷三角形是不是合理的。