0

I have following information in JSON format.

 [
  {
    "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 :

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. So, for A only value is applicable. For B, both values x and y are needed. But for C, only x value is mandatory and user can provide value for y, hence the 2 different methods.

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. If the value if not applicable then i will create method without any parameter.

SuhasD
  • 728
  • 2
  • 7
  • 20

2 Answers2

0

Yes it can be done using Reflection in Java Or You can use javaassit and cglib

Pratham
  • 259
  • 1
  • 8
  • 2
    Reflection asks about classes and their members, you can change fields but you cannot create new ones. but suhashd wants to change method parameters also. That is why I wrote reflection. – Pratham Nov 19 '19 at 04:21
0

yes, you can generate Java bytecode on the fly. CGLib (Github link here) is one option to do that.

Or you can generate Java source code from Json with something like Jackson, and compile that. 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.

jwenting
  • 5,505
  • 2
  • 25
  • 30