【发布时间】:2017-12-24 14:13:19
【问题描述】:
我想知道有没有办法动态地编写方法的主体。即从 XML 或 JSON 读取条件,并根据这些条件定义方法的主体。
如果我没有以正确的方式表达示例,请原谅我。
例如:
def read(conds: Array[String])={
var str = ""
for(i <- 0 to conds.length - 1){
if(conds(i) == "1"){
//add if code to str
//if(){
//if cond code here
//}
}else if(conds(i) == "2"){
//add else if code to str
//else if(){
//else if cond code here
//}
}else if(conds(i) == "3"){
//add else code to str
//else{
//else code here
//}
}
}
//at the end str has multiple conditions
//Ex:
//str = "if(){....}"+
//"esle if(){....}"+
//"esle if(){....}"+
//"esle if(){....}"+
//"esle{....}"
//so all the code present in string should be body of method
}
【问题讨论】:
-
没有。为什么不能只写一个普通的 if 语句呢?
-
因为我必须在xml或者json输入的基础上构建这些条件。有时可能有几个条件,有时可能有 n 个条件。
-
我不确定你的意思,但你能不能只保留一个布尔变量并在你得到的条件下不断地
and它?除此之外,不存在eval之类的功能。 -
抽象读取方法/函数呢?
-
@Sam,所以基本上你可以根据需要构建
str,你的问题是关于从str生成编译代码并运行它的方法,对吧?如果这是你的意图,那么你需要去这里stackoverflow.com/questions/12122939/…
标签: java scala dynamic reflection runtime