简体   繁体   English

Java 动态方法创建

[英]Java dynamic method creation

I have following information in JSON format.我有以下 JSON 格式的信息。

 [
  {
    "name": "A",
    "value": {
      "isValueApplicable": "true"
    }
  },
  {
    "name": "B",
    "parameters": [
      {
        "name": "x",
        "isMandatory": "true"
      },
      {
        "name": "y",
        "isMandatory": "true"
      }
    ]
  },
  {
    "name": "C",
    "parameters": [
      {
        "name": "x",
        "isMandatory": "true"
      },
      {
        "name": "y",
        "isMandatory": "false"
      }
    ]
  }
]

What I want is, a class is created with following methods:我想要的是,使用以下方法创建 class:

public Structure getA (String value) {
}

public Structure getB (String xValue, String yValue) {
}

public Structure getC (String xValue) {
}

public Structure getC (String xValue, String yValue) {
}

The important part here is, these methods should be created dynamically based on the information given in JSON.这里重要的部分是,这些方法应该根据 JSON 中给出的信息动态创建。 So, for A only value is applicable.因此,对于 A 只有值适用。 For B, both values x and y are needed.对于 B,需要值 x 和 y。 But for C, only x value is mandatory and user can provide value for y, hence the 2 different methods.但是对于 C,只有 x 值是强制性的,用户可以为 y 提供值,因此有两种不同的方法。

Q. Is it possible in java to generate the methods at compile time after reading the JSON, like if the parameters are mandatory i will create method with those many parameters.问:在 java 中是否可以在读取 JSON 后在编译时生成方法,就像如果参数是强制性的,我将创建具有那么多参数的方法。 If the value if not applicable then i will create method without any parameter.如果该值不适用,那么我将创建不带任何参数的方法。

Yes it can be done using Reflection in Java Or You can use javaassit and cglib是的,它可以使用 Java 中Reflection in Java来完成,或者您可以使用javaassitcglib

yes, you can generate Java bytecode on the fly.是的,您可以即时生成 Java 字节码。 CGLib ( Github link here ) is one option to do that. CGLib(此处为 Github 链接)是一种选择。

Or you can generate Java source code from Json with something like Jackson, and compile that.或者,您可以使用 Jackson 从 Json 生成 Java 源代码,然后编译它。 Here's one example. 这是一个例子。

I'm sure there are more ways, but yes, it's certainly possible.我敢肯定还有更多方法,但是是的,这当然是可能的。

Of course the Json you're showing is corrupt so would never yield anything but a parser error.当然,您显示的 Json 已损坏,因此除了解析器错误外,不会产生任何结果。

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

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