Java 仅当
我有一个大于30个方法的实用程序类,是否可以向一个类的所有方法添加一个检查,并且只有当检查通过时,函数中的代码才能执行?有什么方便的方法,我可以在一个地方定义检查,然后每次向该类添加新函数时,都应用相同的检查吗?任何时候,只要您必须对一组单元(例如方法、类、字段)应用一个通用行为,并且您不想在任何地方编写多个相同的代码,aspectJ就是最好的选择 我已经创建了一个演示运行供您参考,希望这足以满足您的需要Java 仅当,java,android,Java,Android,我有一个大于30个方法的实用程序类,是否可以向一个类的所有方法添加一个检查,并且只有当检查通过时,函数中的代码才能执行?有什么方便的方法,我可以在一个地方定义检查,然后每次向该类添加新函数时,都应用相同的检查吗?任何时候,只要您必须对一组单元(例如方法、类、字段)应用一个通用行为,并且您不想在任何地方编写多个相同的代码,aspectJ就是最好的选择 我已经创建了一个演示运行供您参考,希望这足以满足您的需要 import static java.lang.annotation.RetentionP
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;
}
}
}
听起来你需要使用AOP。