Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I dynamically create a Java object in the run time via JSON?

Tags:

java

json

object

For example, I have a JSON format like this:

{"class":"MySpecialClass", "attri1":"value1", "attri2":"value2"}

I would like to create a Object, which is a MySpecialClass Object, and get two attribute, attri1 and attri2 with the value of value1 and value2.

Here is the requirement:

  1. I have a class file, named, MySpecialClass, and have attri1, and attri2, can I create this object, and assign the value in this?

  2. I DONT'T have the class file MySpecialClass, I would like to generate it on the runtime, is this possible to do so? Thanks.

like image 813
DNB5brims Avatar asked Aug 03 '12 08:08

DNB5brims


1 Answers

Your first case is perfectly feasible using any Java/JSON parser.

Your second case is possible, but hard work.

You can construct classes at runtime using bytecode engineering - e.g. using Apache BCEL. Note that the JSON will contail fields only, and not behaviour nor type.

like image 98
Brian Agnew Avatar answered Oct 11 '22 19:10

Brian Agnew