简体   繁体   中英

Dynamically inject fields on Java objects using ByteBuddy

I have this code which I need (it) to inject fields at runtime:

public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    TestEntity entity = (TestEntity) source;
    entity.getPropertyMap().forEach((fieldName, fieldValue) -> {
      // "fieldName" is an arbritary name not known at compile time
      injectFieldTo(source, fieldName, fieldValue);
    });
    entity.setPropertyMap(null);
    super.marshal(source, writer, context);
}

Is there a way to do this in Java using ByteBuddy ? And if not directly (even with just a clone object), what can be done as such fields can be injected into the object? What is the process?

TestEntity.java

public class TestEntity implements Serializable {
  private String entityType;
  private String entityId;
  private String dateCreated;
  private String dateUpdated;
  private Boolean publicRead;
  private Boolean publicWrite;
  private Map<String, Object> propertyMap;
}

You would need to define a new class to define fields. You can subclass the existing class by new ByteBuddy().subclass(...) or use new ByteBuddy().rebase(...) to copy the existing class and rename it, in case assignability is not an issue. You define new fields using the defineField API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM