我可以在运行时通过JSON动态创建Java对象吗? [英] Can I dynamically create a Java object in the run time via JSON?
问题描述
例如,我具有这样的JSON格式:
For example, I have a JSON format like this:
{"class":"MySpecialClass","attri1":"value1","attri2":"value2"}
{"class":"MySpecialClass", "attri1":"value1", "attri2":"value2"}
我想创建一个对象,它是一个MySpecialClass
对象,并获得两个值为value1
和value2
的属性attri1
和attri2
.
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
.
这是要求:
-
我有一个名为
MySpecialClass
的类文件,并且具有attri1
和attri2
,我可以创建该对象并在其中分配值吗?
I have a class file, named,
MySpecialClass
, and haveattri1
, andattri2
, can I create this object, and assign the value in this?
我DONT'T
有类文件MySpecialClass
,我想在运行时生成它,这有可能吗?谢谢.
I DONT'T
have the class file MySpecialClass
, I would like to generate it on the runtime, is this possible to do so? Thanks.
推荐答案
使用任何Java/JSON解析器,第一种情况都是完全可行的.
Your first case is perfectly feasible using any Java/JSON parser.
您的第二种情况是可能的,但要努力.
Your second case is possible, but hard work.
您可以在运行时使用 bytecode engineering 构造类-例如使用 Apache BCEL .请注意,JSON仅包含字段,而不包含行为或类型.
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.
这篇关于我可以在运行时通过JSON动态创建Java对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!