gpt4 book ai didi

java - 仅当满足以下条件时才执行类中的所有方法

转载 作者:行者123 更新时间:2023-12-02 11:08:37 26 4
gpt4 key购买 nike

我有一个包含超过 30 个方法的实用程序类,是否可以向类的所有方法添加 1 个检查,并且仅当检查通过时才会执行函数中的代码?是否有一些方便的方法可以让我在一个地方定义检查,然后每次向该类添加新函数时都应用相同的检查?

最佳答案

任何时候你必须对一组单元(比如方法、类、字段)应用一个共同的行为,并且你不想在任何地方编写大量相同的代码,aspectJ 就是你的最佳选择。

我创建了一个演示运行供您引用,希望这能满足您的需求。

import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

public class ConditionalExcecution {

public static void main(String[] args) {
ControlSlave controlSlave1 = new ControlSlave();
controlSlave1.usable = true;
System.out.println(controlSlave1.sum(1, 2));
controlSlave1.print("HelloWorld");

ControlSlave controlSlave2 = new ControlSlave();
System.out.println(controlSlave2.sum(1, 2));
controlSlave2.print("HelloWorld");
}

}

/**
* Conditional Method Execution Class
* @author AmithKumar
*
*/
@Conditional
class ControlSlave {
boolean usable;

public int sum(int a, int b) {
return a + b;
}

public void print(String s) {
System.out.println(s);
}
}

/**
* Annotation to mark class usable
* @author AmithKumar
*
*/
@Target({ElementType.TYPE})
@Retention(RUNTIME)
@interface Conditional {
}

@Aspect
class ControlMaster {

/**
* decision controller to check condition to continue method execution
*
* @param proceedingJoinPoint
* @return Object
* @throws Throwable
*/
@Around("execution(* *(..)) && @within(Conditional)")
public Object check(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// get object
ControlSlave controlSlave = (ControlSlave) proceedingJoinPoint.getThis();
if (controlSlave.usable) {
return proceedingJoinPoint.proceed();
} else {
return null;
}
}
}

关于java - 仅当满足以下条件时才执行类中的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50745887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com