如何创建一个值为 Method 类型的枚举。

huangapple 未分类评论48阅读模式
英文:

How to have enum with a value of type Method

问题

我想要在数据类型和方法名之间建立映射关系。对于特定的数据类型,将调用不同的方法。因此,我想以枚举的形式存储这些信息。您可以如何实现呢?例如,对于 CHECKBOX 类型,我想要调用一个名为 checkboxsimilarity 的方法,应该如何在下面的结构中存储和访问呢?

public enum MethodNames {
    CHECHBOX(Method.checkboxsimilarity);
    
    private final Method method;
    
    private MethodNames(Method method) {
        this.method = method;
    }
    
    public Method getMethod() {
        return method;
    }
}
英文:

I want to have a mapping between datatype and the methodname. As for a particular datatype a different method would be called. So, I want to store that in form of enum. How can I achieve it. For example for CHECKBOX type I want to call a method with the name checkboxsimilaity, how should I store store and access in the structure below.

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

}

答案1

得分: 0

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

public enum ElementType {
    CHECKBOX(() -> {
        System.out.println("在此处选择复选框或调用所需方法");
        return "已选";
    }),
    TEXT_FIELD(() -> {
        System.out.println("在文本字段中输入内容或调用所需方法");
        return "已输入";
    });

    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();
}

或者,你也可以在其他地方实现方法,让枚举带有一个字符串参数(即方法名),然后使用反射从相应类中调用具有相应名称的方法。

英文:

You may try to use functional interfaces to associate some functionality with enum values:

public enum ElementType {
    CHECKBOX(() -&gt; {
        System.out.println(&quot;Select checkbox here or call needed method&quot;);
        return &quot;selected&quot;;
    }),
    TEXT_FIELD(() -&gt; {
        System.out.println(&quot;Type something into text field or call needed method&quot;);
        return &quot;typed&quot;;
    });
    
    private Supplier&lt;String&gt; action;

    ElementType(Supplier&lt;String&gt; action) {
        this.action = action;
    }
    
    public String executeAssociatedAction() {
        return action.get();
    }
}

And you can do almost whatever you want there.
The invoking will than be:

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

Alternatively, you can have methods implemented somewhere else, have enum with a string as a parameter (which will be the method name) and use reflection to call a method with the corresponding name from the corresponding class.

huangapple
  • 本文由 发表于 2020年5月19日 18:08:50
  • 转载请务必保留本文链接:https://java.coder-hub.com/61888433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定