在java中的同一类的“每个”方法之前执行一个函数

Flo*_*ain 8 java

我在一个类中有几个方法需要将布尔值设置为 true 才能正确执行。

我可以if在每个方法中编写语句,但是如果我或其他人想要添加另一种方法,则不方便。我或他可以忘记支票。

java中有没有办法在类中的其他方法之前执行一个方法(就像JUnit所做的那样@BeforeEach)?

编辑:提出了许多非常有趣的技术/答案/概念。当我了解他们时,我会与他们取得联系。谢谢。

Sai*_*sif 5

让我们创建一个方法turnBooleanTrue(),其中有效地boolean设置为 true 以便正确执行该方法。

然后,您可以编写自己的InvocationHandler来拦截对您的对象的调用,然后反射地(使用反射 API)首先调用turnBooleanTrue()方法,然后调用被调用的方法。

看起来像这样

public class MyClassInvocationHandler implements InvocationHandler {

    // initiate an instance of the class
    MyClass myClass = new MyClassImpl();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {

        // look up turnBooleanTrue() method
        Method turnBooleanTrue = myClass.getClass().getMethod("turnBooleanTrue");

        // invoke the method
        turnBooleanTrue.invoke(...); // toggle the boolean

        // invoke the method to which the call was made
        // pass in instance of class
        Object returnObj = method.invoke(myClass, args);

        return returnObj;
}
Run Code Online (Sandbox Code Playgroud)

编辑

添加了一些行来MyClass初始化一个对象。您需要一些东西来调用方法并维护状态。在上面的代码示例中更改utilmyClass


Flo*_*ain 1

考虑到我的用例,使用 AOP 或其他概念有点矫枉过正。所以我基本上对每个功能都做了检查。