依赖
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.25.0-GA</version>
</dependency>
代码
import javassist.*;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.StringMemberValue;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.util.ReflectionUtils;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class DynamicObjectUtils {
public static Class<?> prepareClass(final String className, List<String> fields) throws CannotCompileException {
ClassPool pool = ClassPool.getDefault();
CtClass evalClass = pool.makeClass(className + UUID.randomUUID().toString());
for ( String field : fields) {
CtField ctField = CtField.make("public java.lang.String " + field + ";", evalClass);
evalClass.addField(ctField);
evalClass.addMethod(CtNewMethod.getter("get" + capitalize(field), ctField));
evalClass.addMethod(CtNewMethod.setter("set" + capitalize(field), ctField));
}
ClassFile ccFile = evalClass.getClassFile();
ConstPool constPool = ccFile.getConstPool();
AnnotationsAttribute bodyAttr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
Annotation bodyAnnot = new Annotation("org.springframework.data.mongodb.core.mapping.Document", constPool);
bodyAnnot.addMemberValue("collection", new StringMemberValue(className, constPool));
bodyAttr.addAnnotation(bodyAnnot);
ccFile.addAttribute(bodyAttr);
return evalClass.toClass();
}
private static String capitalize(String field) {
field = field.substring(0, 1).toUpperCase() + field.substring(1);
return field;
}
public static Object createObject(Class<?> clazz, List<String> fields, Map<String, Object> values) {
try {
Object obj = clazz.newInstance();
for (String field : fields) {
ReflectionUtils.setField(clazz.getField(field), obj, values.get(field));
}
return obj;
} catch (Exception e) {
return new BeanCreationException(String.format("class name: %s", clazz));
}
}
}