[英]Java can I map a variable to a method of an object
我有一個字符串形式為“ 1 = xyz,2 = zyx,3 = blah”和一個對象
public class Foo{
String a,b,c
/*gets and sets*/
}
我想實例化此對象,以便a = xyz,b = zyx和c = blah。 我到目前為止所擁有的是
for(String[] split1 : originalString.split(","){
for(String[] split2 : split1.split("="){
if(split2[0] == 1){foo.setA(split2[1])}
if(split2[0] == 2 {...}
}
}
我想知道的是,是否有比使用成百上千的if語句更干凈的方法? 有沒有一種方法可以在原始列表中的鍵之間用我的pojo中的setter創建一個Map?
我發現了一些較舊的問題,但是我想知道Java 8是否為此添加了一些東西。 我不想使用反射(我也不應該)
是的,您可以使用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]);
}
}
}
}
您也可以使用反射,但是最好避免使用反射,因為反射會使錯誤很難檢測到,並且不太可能在運行時由JIT優化。
我創建了一個類似1 =“ a”,2 =“ b”,3 =“ c”的Map,並使用它來將鍵轉換為pojo的字段名稱。
然后我使用了Gson的以下內容
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(responseMap);
Foo trade = gson.fromJson(jsonElement, Foo.class);
如果允許使用groovy,則只需使用默認的基於地圖的構造函數。 建議@chrylis提出該方法。
可以使用正則表達式從輸入字符串中清除不需要的字符,然后將其分割。 請注意,輸出數組中的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.