仅在类中执行所有方法

时间:2018-06-07 16:14:26

标签: java android

我有一个带有> 30方法的实用程序类,是否可以对类的所有方法添加1个检查,并且只有在检查通过时才会执行函数中的代码?有什么方便我可以在一个地方定义检查,然后每次将新功能添加到该类时,相同的检查是否适用?

1 个答案:

答案 0 :(得分: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;
        }
    }
}
相关问题