-1

I need to do some "bytecode hacking" to inject something into a POJO without adding a "visible" property.

Consider this code:

public class Entity {
    private Multimap<String, Entity> linkMap;
    public void setLink(String linkName, Entity entity) {
       if(linkMap == null) {
        linkMap = HashMultimap.create();
       }
       boolean isSet = false;
       entity = byteCodeHack(entity, false);
       linkMap.put(linkName, entity);
    }
    public void addLink(String linkName, Entity entity) {
       if(linkMap == null) {
        linkMap = HashMultimap.create();
       }
       boolean isSet = true;
       entity = byteCodeHack(entity, isSet);
       linkMap.put(linkName, entity);
    }
}

Where there are two types of link, one is "set" and one is "not set (or multi)" and there's no way to determinate if the "link" is a "set" or "not set" even if the Multimap contains only one entry for a given link name, it does not mean that it is a "set" it could be an "addLink" which is just one. The point here is the underlying database can link objects one-to-one (set) or one-to-many (add). And the stage that will process this Entity needs to know from the Multimap which database operation to do, "set" or "add" -- but as mentioned that can't be inferred by just iterating over the Multimap.

So my strategy is to inject a value into the entity before inserting it to the Multimap, the byteCodeHack method.

What would be the best way to implement this?

quarks
  • 33,478
  • 73
  • 290
  • 513
Fireburn
  • 981
  • 6
  • 20

1 Answers1

1

An alternative solution without class enhancing is to add an additional method to set the Multimap in such as way when it is "set" it will first remove all the other elements existing, then another method "add" to just add causing to have multiple similar keys:

  public void addLink(String linkName, Entity entity) {
    linkMap.put(linkName, entity);
  }

  public void setLink(String linkName, Entity entity) {
    Collection<Entity> oldValues = linkMap.get(linkName);
    if(Objects.nonNull(oldValues)) {
      linkMap.remove(linkName, oldValues);
    }
    linkMap.put(linkName, entity);
  }

If class enhancing is really required, it can be done through https://bytebuddy.net/#/ library.

quarks
  • 33,478
  • 73
  • 290
  • 513