A Case of Dynamic Generation of bean from java

  • 2021-08-21 20:16:57
  • OfStack

Recently, I made a requirement, and the bean in the requirement is only used to generate json once, so I want to generate it dynamically through configuration. After checking 1, java really has this implementation.

java dynamically generates javabean, which can only generate attributes and corresponding set/get methods, but cannot generate other methods.


import org.assertj.core.internal.cglib.beans.BeanGenerator;
import org.assertj.core.internal.cglib.beans.BeanMap;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
 * Created by wangpengzhi1 on 2018/1/2.
 */
public class BeanCeater {
 public static void main(String[] args) throws ClassNotFoundException {
  System.out.println("Generate JavaBean");
  Map properties = new HashMap();
  properties.put("id", Class.forName("java.lang.Integer"));
  properties.put("name", Class.forName("java.lang.String"));
  properties.put("address", Class.forName("java.lang.String"));
  Object stu = generateObject(properties);
  System.out.println("Set values");
  setValue(stu, "id", 123);
  setValue(stu, "name", "454");
  setValue(stu, "address", "789");
  System.out.println("Get values");
  System.out.println(">> " + getValue(stu, "id"));
  System.out.println(">> " + getValue(stu, "name"));
  System.out.println(">> " + getValue(stu, "address"));
  System.out.println("Show all methods");
  Method[] methods = stu.getClass().getDeclaredMethods();
  for(Method method : methods) {
   System.out.println(">> " + method.getName());
  }
  System.out.println("Show all properties");
  Field[] fields = stu.getClass().getDeclaredFields();
  for(Field field : fields) {
   System.out.println(">> " + field.getName());
  }
 }
 private static Object generateObject(Map properties) {
  BeanGenerator generator = new BeanGenerator();
  Set keySet = properties.keySet();
  for(Iterator i = keySet.iterator(); i.hasNext();) {
   String key = (String)i.next();
   generator.addProperty(key, (Class)properties.get(key));
  }
  return generator.create();
 }
 private static Object getValue(Object obj, String property) {
  BeanMap beanMap = BeanMap.create(obj);
  return beanMap.get(property);
 }
 private static void setValue(Object obj, String property, Object value) {
  BeanMap beanMap = BeanMap.create(obj);
  beanMap.put(property, value);
 }
}

The code is not difficult to understand, and you need to copy it yourself.

Supplement: spring tool class ReflectionUtils gets all fields of bean

In the past, when we want to get the field of the current class and all the parent classes, we all recursively look for it straight up until Object. Personally, I think this method is too low. Is there a better way? Or jdk actually has this method, but I don't know. Today, I saw the implementation of spring, which is also one. There is really no better way?


public static void doWithFields(Class<?> clazz, ReflectionUtils.FieldCallback fc, @Nullable ReflectionUtils.FieldFilter ff) {
    Class targetClass = clazz;
 
    do {
      Field[] fields = getDeclaredFields(targetClass);
      Field[] var5 = fields;
      int var6 = fields.length;
 
      for(int var7 = 0; var7 < var6; ++var7) {
        Field field = var5[var7];
        if (ff == null || ff.matches(field)) {
          try {
            fc.doWith(field);
          } catch (IllegalAccessException var10) {
            throw new IllegalStateException("Not allowed to access field '" + field.getName() + "': " + var10);
          }
        }
      }
 
      targetClass = targetClass.getSuperclass();
    } while(targetClass != null && targetClass != Object.class); 
  }
 
  private static Field[] getDeclaredFields(Class<?> clazz) {
    Assert.notNull(clazz, "Class must not be null");
    Field[] result = (Field[])declaredFieldsCache.get(clazz);
    if (result == null) {
      try {
        result = clazz.getDeclaredFields();
        declaredFieldsCache.put(clazz, result.length == 0 ? NO_FIELDS : result);
      } catch (Throwable var3) {
        throw new IllegalStateException("Failed to introspect Class [" + clazz.getName() + "] from ClassLoader [" + clazz.getClassLoader() + "]", var3);
      }
    }
 
    return result;
  }

Related articles: