简体   繁体   English

如何将String映射到未知返回类型的java方法引用?

[英]How to map a String to a java method reference for unknown return type?

I want to map a String to a method reference. 我想将String映射到方法引用。 The problem is that this method can return void or boolean . 问题是这个方法可以返回voidboolean

I was using @FunctionalInterface but seems it can have only one method (I would need one for void and one for boolean ?). 我正在使用@FunctionalInterface但似乎它只能有一个方法(我需要一个用于void ,一个用于boolean ?)。

Below is the code I have so far. 下面是我到目前为止的代码。 The commented lines are what I would like to do. 评论的行是我想做的。


@FunctionalInterface
interface MethodParser <T1, T2> {
    public void apply(T1 arg1, T2 arg2);
}

public class OperatorParser {

    public static Map<String, MethodParser> INTEGER = new HashMap<String, MethodParser>();

    public static void buildInteger() {
        MethodParser<Integer_, Integer> plus = (pObj, pValue) -> pObj.plus(pValue);
        MethodParser<Integer_, Integer> minus = (pObj, pValue) -> pObj.minus(pValue);

        // MethodParser<Integer_, Integer> grThan = (pObj, pValue) -> pObj.greaterThan(pValue);
        // MethodParser<Integer_, Integer> lessTh = (pObj, pValue) -> pObj.lessThan(pValue);

        OperatorParser.INTEGER.put("+", plus);
        OperatorParser.INTEGER.put("-", minus);

        // OperatorParser.INTEGER.put(">", grThan);
        // OperatorParser.INTEGER.put("<", lessTh);
    }

}

The object Integer_ represents a integer number and has void methods ( plus(int) and minus(int) ) that changes the value of the object and boolean methods ( greaterThan(int) and lessThan(int) ) that returns a value. 对象Integer_表示整数,并且具有更改对象value的void方法( plus(int)minus(int) )以及返回valueboolean方法( greaterThan(int)lessThan(int) )。

The MethodParser interface is just one way I found to map a String to a method reference. MethodParser接口只是我发现将String映射到方法引用的一种方法。 I use it to map a given String to a method that already exists somewhere else. 我用它来将给定的String映射到已经存在于其他地方的方法。

Note: Some similar questions I have tried (these don't worked for me): 注意:我尝试过一些类似的问题(这些问题对我不起作用):

Make a method for void and one for boolean and a method that includes the condition that tells when to use either. void提供一个方法,为boolean一个方法,并为包含告知何时使用的条件的方法创建一个方法。 I don't know of any method that could have 2 return types. 我不知道任何可能有2种返回类型的方法。 You Can use a POJO class instance to return multiple values with grouping. 您可以使用POJO类实例通过分组返回多个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM