Search code examples
javabyte-buddy

Create classes with variable number of fields


I want to create a set of classes with variable number of fields. What I tried:

private Class<?> generateClass(String clazzName, Map<String, Class<?>> fields) {
    DynamicType.Builder<Object> buddy = new ByteBuddy()
            .subclass(Object.class)
            .name(clazzName);
    
    fields.forEach((k, v) -> {
        buddy.defineField(k, v, Visibility.PRIVATE);
    });
    return buddy.make().load(ClassLoader.getSystemClassLoader()).getLoaded();
}

where parameter clazzName is the class name to be created and key of the fields represent the field name and the value represent the field type.

The issue with the above code is that it creates the class but without any fields. What am I missing?

Also it's possible to generate the public getters from the fields above?


Solution

  • Byte Buddy's API is immutable. You will need to assign the field definitions:

    buddy = buddy.defineField(k, v, Visibility.PRIVATE);
    

    You are basically dropping the changes you made immediately.