java - Create simple POJO classes (bytecode) at runtime (dynamically) -
i've following scenario..
i writing tool run user-entered query against database , return result..
the simplest way return result as: list<string[]>
need take step further.
i need create (at runtime) pojo (or dto) name , create fields , setters , getters , populate data returned , return user among .class
file generated...
so idea here how create simple class(bytecode) @ runtime (dynamically) basic search , found many lib including apache bcel think need more simpler...
what think of that?
thanks.
creating simple pojo getters , setters easy if use cglib:
public static class<?> createbeanclass( /* qualified class name */ final string classname, /* bean properties, name -> type */ final map<string, class<?>> properties){ final beangenerator beangenerator = new beangenerator(); /* use our own hard coded class name instead of real naming policy */ beangenerator.setnamingpolicy(new namingpolicy(){ @override public string getclassname(final string prefix, final string source, final object key, final predicate names){ return classname; }}); beangenerator.addproperties(beangenerator, properties); return (class<?>) beangenerator.createclass(); }
test code:
public static void main(final string[] args) throws exception{ final map<string, class<?>> properties = new hashmap<string, class<?>>(); properties.put("foo", integer.class); properties.put("bar", string.class); properties.put("baz", int[].class); final class<?> beanclass = createbeanclass("some.classname", properties); system.out.println(beanclass); for(final method method : beanclass.getdeclaredmethods()){ system.out.println(method); } }
output:
class some.classname
public int[] some.classname.getbaz()
public void some.classname.setbaz(int[])
public java.lang.integer some.classname.getfoo()
public void some.classname.setfoo(java.lang.integer)
public java.lang.string some.classname.getbar()
public void some.classname.setbar(java.lang.string)
but problem is: have no way of coding against these methods, don't exist @ compile time, don't know you.
Comments
Post a Comment