简体   繁体   English

Java我可以将变量映射到对象的方法吗

[英]Java can I map a variable to a method of an object

I have a string in the form "1=xyz,2=zyx,3=blah", and an object 我有一个字符串形式为“ 1 = xyz,2 = zyx,3 = blah”和一个对象

public class Foo{
    String a,b,c
    /*gets and sets*/
}

I'd like to instantiate this object so that a = xyz, b = zyx, and c = blah. 我想实例化此对象,以便a = xyz,b = zyx和c = blah。 What I have so far is, 我到目前为止所拥有的是

for(String[] split1 : originalString.split(","){
    for(String[] split2 : split1.split("="){
        if(split2[0] == 1){foo.setA(split2[1])}
        if(split2[0] == 2 {...}
    }
}

And what I want to know is, is there a cleaner way to do this than with a bajillion if statements? 我想知道的是,是否有比使用成百上千的if语句更干净的方法? Is there a way to create a Map between the keys in the original list with setters in my pojo? 有没有一种方法可以在原始列表中的键之间用我的pojo中的setter创建一个Map?

I found some older questions on this, but I was wondering if java 8 might have added something for this. 我发现了一些较旧的问题,但是我想知道Java 8是否为此添加了一些东西。 I don't want to use Reflection (nor should I) 我不想使用反射(我也不应该)

Yes, you can use a Map<String, BiConsumer<Foo, String>> : 是的,您可以使用Map<String, BiConsumer<Foo, String>>

public class StringProcessor {
    private final Map<String, BiConsumer<Foo, String>> setMethods;

    public StringProcessor() {
        Map<String, BiConsumer<Foo, String>> methodMap = new HashMap<>();
        methodMap.put("a", Foo::setA);
        methodMap.put("b", Foo::setB);
        methodMap.put("c", Foo::setC);

        this.setMethods = Collections.unmodifiableMap(methodMap);
    }

    // ...

    public void processString(String originalString,
                              Foo foo) {

        for (String[] split1 : originalString.split(",")) {
            for (String[] split2 : split1.split("=")) {
                BiConsumer<Foo, String> setMethod = setMethods.get(split2[0]);
                setMethod.accept(foo, split2[1]);
            }
        }

    }
}

You could also use reflection, but that is best avoided, as reflection makes errors much harder to detect and it is less likely to be optimized at runtime by the JIT. 您也可以使用反射,但是最好避免使用反射,因为反射会使错误很难检测到,并且不太可能在运行时由JIT优化。

I created a Map like 1="a", 2="b", 3="c", and used that to translate the keys into the pojo's field names. 我创建了一个类似1 =“ a”,2 =“ b”,3 =“ c”的Map,并使用它来将键转换为pojo的字段名称。

Then I used the following from Gson 然后我使用了Gson的以下内容

Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(responseMap);
Foo trade = gson.fromJson(jsonElement, Foo.class);

If I'd been allowed to use groovy, I'd simply use the default map-based constructor. 如果允许使用groovy,则只需使用默认的基于地图的构造函数。 Props to @chrylis for suggesting that approach. 建议@chrylis提出该方法。

can use Regular Expression to blank out the not needed characters from the input string and then splitting it. 可以使用正则表达式从输入字符串中清除不需要的字符,然后将其分割。 Note the String elements in the output array might need trimming. 请注意,输出数组中的String元素可能需要修剪。

import java.util.regex.*;

public class StringRegex{
 public static void main(String[] args){
  String input = "1=xyz,2=zyx,3=blah";
  String notNeeded = "([1234567890=])";      //characters not needed 0-9 and =

  Pattern p = Pattern.compile(notNeeded);
  Matcher m = p.matcher(input);

  String output = m.replaceAll(" ");  //blank out the notNeeded characters
  System.out.println(output);         //gives:   xyz,  zyx,  blah

  String[] outputArr = output.split(",");

  for (String s:outputArr)
    System.out.println(s);
 }
}

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

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