Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create dynamic / runtime (and simple) bean from JSON String

In what way can Java generate a Bean (not just a Map object)--a bean with fields, getters, and setters from a JSON String.

Here's the code I am trying now using ByteBuddy (non-working code/error):

        Object contextObject = new ByteBuddy()
            .subclass(Object.class)
            .defineField("date", String.class, Modifier.PUBLIC)
            .defineMethod("getDate", Void.TYPE, Modifier.PUBLIC)
            .intercept(FieldAccessor.ofField("date"))
            .make()
            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
            .getLoaded()
            .newInstance();
        BeanUtils.setProperty(contextObject, "date", "August 1, 2017");

However, due to the "wired" natured for ByteBuddy, I am not sure how flexible it can be to generate a dynamic bean from JSON.

like image 794
quarks Avatar asked Sep 11 '25 02:09

quarks


1 Answers

Byte Buddy is a generic class generation tool, of course you can define a bean using it. You just need to loop over your properties. Something like the following:

DynamicType.Builder<?> builder = ...
for ( ... ) {
  Class<?> type = ...
  String name = ...
  builder = builder.defineField(name, type, Visibility.PRIVATE)
                   .defineMethod("get" + name, type, Visibility.PUBLIC)
                   .intercept(FieldAccessor.ofBeanProperty())
                   .defineMethod("set" + name, void.class, Visibility.PUBLIC)
                   .withParameters(type)
                   .intercept(FieldAccessor.ofBeanProperty());
}

This has become such a common request that I have added a convenience method to the builder API for the next release:

DynamicType.Builder<?> builder = ...
for ( ... ) {
  Class<?> type = ...
  String name = ...
  builder = builder.definedProperty(name, type);
}
like image 54
Rafael Winterhalter Avatar answered Sep 12 '25 18:09

Rafael Winterhalter