Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

java - 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?

question from:https://stackoverflow.com/questions/65936920/create-classes-with-variable-number-of-fields

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...