1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.