Create simple POJO classes (bytecode) at runtime (dynamically)

后端 未结 5 1222
遥遥无期
遥遥无期 2020-11-27 05:24

I\'ve the following scenario..

I am writing some tool that run user-entered query against the database and return the result..

The simplest way is to return

5条回答
  •  半阙折子戏
    2020-11-27 06:04

    I have used ASM for this in the past. What I like is the ASMifier which can create code to generate a class. e.g. I create a generic POJO in java code with one field of every type in Java and use ASMifier to create the Java code to create this from byte code and used it as a template to generate an arbitary POJO.

    As @Michael suggests, you may want to add a non-reflective way to get arbitary fields. e.g.

    public Set fieldNames();
    public Object getField(String name);
    public void setField(String name, Object name);
    

    Why do you want to do this? There are ways you can make use a Map style objects more efficient than using a regular map.

    Another approach is to generate the Java source using Velocity and compile the code using the Compiler API. Its a pain to use so I wrote a wrapped for it here Essence JCF The only read advantage to using this approach is that you can easily debug your generated code. (The library has the option of saving the java code to somewhere the debugger can find it so when you step into the generated code)

提交回复
热议问题