【问题标题】:How to have enum with a value of type Method如何使用 Method 类型的值进行枚举
【发布时间】:2020-05-19 10:08:50
【问题描述】:

我想在数据类型和方法名之间建立一个映射。对于特定的数据类型,将调用不同的方法。所以,我想以枚举的形式存储它。我怎样才能实现它。例如对于 CHECKBOX 类型我想调用一个名为 checkboxsimilaity 的方法,我应该如何在下面的结构中存储存储和访问。

public enum MethodNames{
    //CHECHBOX with the value checkboxsimilaity (of type method)
    public final Method name;

}

【问题讨论】:

标签: java enums


【解决方案1】:

您可以尝试使用函数式接口将某些功能与枚举值相关联:

public enum ElementType {
    CHECKBOX(() -> {
        System.out.println("Select checkbox here or call needed method");
        return "selected";
    }),
    TEXT_FIELD(() -> {
        System.out.println("Type something into text field or call needed method");
        return "typed";
    });

    private Supplier<String> action;

    ElementType(Supplier<String> action) {
        this.action = action;
    }

    public String executeAssociatedAction() {
        return action.get();
    }
}

您几乎可以在那里做任何您想做的事。 调用将是:

public static void main(String[] args) {
    ElementType.CHECKBOX.executeAssociatedAction();
}

或者,您可以在其他地方实现方法,将带有字符串的枚举作为参数(这将是方法名称)并使用反射从相应的类中调用具有相应名称的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 2018-10-18
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    相关资源
    最近更新 更多