如何从javaenum调用函数?

liwlm1x9  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(327)

我试图理解来自javaenum的静态方法调用是如何工作的。
查看此“工作示例”的完整代码
我有下面的场景工作,我不知道为什么

public enum Condition {
    GREATER_THAN(PredicateBuilder::generateGreaterThan, ">"),
    more values...
    private Condition(BiFunction<PredicateBuilder, PredicateContent<?>, Predicate> predicate, String operator) {
        this.operator = operator;
        this.predicate = predicate;
    }

这是 predicate 生成器,它是由spring中的 @Component 实现的接口:

@Component
public class PredicateLogicalBuilder<V extends Comparable> implements PredicateBuilder<V> {

    @Override
    public Predicate generateGreaterThan(PredicateContent<V> predicateContent) {
        return predicateConversion(predicateContent,Condition.GREATER_THAN);
    }
}

上述条件枚举中的静态引用没有抱怨:

Non-static method cannot be referenced from a static context

我不知道为什么,因为现在我正在尝试做类似的事情,但是失败了,因为方法的静态引用不是静态的。在上面的代码中也不是静态的。
我正在尝试的代码:

public interface MethodCalls<T> {
    void randomMethod(T content);
}

@Component
public class TestEnumMethoCalls implements MethodCalls<SomeBean> {
    @Override
    public void randomMethod(SomeBean content){
        System.out.println("Works!!!!");
    }
}

public enum NotificationType {
    ENUM_TEST_1(MethodCalls::randomMethod);

    public final Function<SomeBean,Void> method;

    private NotificationType(Function<SomeBean,Void> method){
       this.method=method;
    }
}

public class TestClass{
    public void testMethtod(){
        NotificationType.ENUM_TEST_1.method.apply(new SomeBean())
    }
}

这段代码无法说出 Non-static method cannot be referenced from a static context :

ENUM_TEST_1(MethodCalls::randomMethod);

我想要两个答案:
“工作示例”代码的工作原理。
如果当前测试必须使用 MethodCalls 如何将di注入enum(这是一个静态上下文,所以我知道如果不是不可能的话,这可能会很棘手)。

zd287kbt

zd287kbt1#

感谢您的帮助,现在我明白了为什么我的“工作示例”有效,以及如何“修复”我当前的问题:
为了解决这个问题,我必须传递一个接口实现的示例,正如前面指出的,枚举只能访问静态方法或者对象的一个示例来访问该方法。
最终代码

public enum NotificationType {
    ENUM_TEST_1(MethodCalls::randomMethod);

    public final BiFunction<MethodCalls,SomeBean,Void> method;

    private NotificationType(BiFunction<MethodCalls,SomeBean,Void> method){
        this.method=method;
    }
}

所以当我调用apply时,它看起来是这样的:

public class TestClass{
    @Autowired MethodCalls methodCalls;
    public void testMethtod(){
        NotificationType.ENUM_TEST_1.method.apply(methodCalls,new SomeBean())
    }
}

如果有人找到一个更干净的方法,我会很感激的。

相关问题