【问题标题】:is there any way to write functions or methods body dynamically in scala or java有没有办法在scala或java中动态编写函数或方法体
【发布时间】: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


【解决方案1】:

我们正在使用Scala macros 自动从 json 文件生成我们的 api。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多