如果你想從name = Paul AND age = 16 AND country = china
創建類的實例樣的腳本,那麼你可以自己創建的方法
public <T> T builder(Class<T> clazz, String line)
throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
T instance = clazz.newInstance();
String[] exps = line.split("AND");
for (String exp : exps) {
String[] tokens = exp.split("=", 2);
// TODO check if token has length==2
tokens[0] = tokens[0].trim();
tokens[1] = tokens[1].trim();
String methodName = "set"
+ (("" + tokens[0].charAt(0)).toUpperCase())
+ tokens[0].substring(1);
Method m1 = instance.getClass().getMethod(methodName, String.class);
m1.invoke(instance, tokens[1]);
}
return instance;
}
,當你調用它builder(Person.class,"name = Paul AND age = 16 AND country = china")
你會得到Person
類的實例與填充字段name
,age
和country
。
這是你在找什麼?
是你可以,但如果這只是你需要做的,你不需要ANTLR – user902383
確定。但是有沒有特定的語法?要在語法文件中寫入這些內容? – user2144555
如果這個'名字=保羅和年齡= 16和國家=中國;'是你要分析一下,那麼所有你需要做的是擺脫掉';從行末'性格,分裂你行「」你可以使用'String.split()',然後你的數組中的每個條目再次在'=''上分開。然後通過使用反射從實例中獲得setter並設置正確的參數。你想創建你的類,源文件或二進制文件的實例嗎? – user902383