AspectJ / Generate methods using compile-time refl

2019-07-22 00:50发布

问题:

I just heard of AspectJ and it doesn't look too easy to understand, so I want to know beforehand if it (or anything else) will help me with my problem or not.

I have bunch of simple POJO classes and want to write binary serializers for them but without writing Write/Read methods by hand for each class. I could've done so with help of reflection but that will affect runtime performance. I believe I need something similar to Macroses in Scala with compile-time reflection and quasiquotes.

Update: I'm unable to use any serialization available, because I have custom binary protocol which I can't modify (online game)

Update 2:

Example POJO with it's read, write and some helper methods. Not final version, there possibly could be some annotations, for example, but general structure should be the same. I also omitted inheritance for simplicity, in reality LoginPacket extends CommandPacket class which in turn extends Packet class.

public class LoginPacket {
    public short length;
    public int sessionId;
    public short command;
    public short error;
    public String reason;

    private String getString(ByteBuffer data) {
        short length = data.getShort();
        byte[] stringData = new byte[length];
        data.get(stringData);
        return new String(stringData, "UTF-8");
    }

    private void putString(ByteBuffer data, String someString) {
        data.putShort(someString.length());
        byte[] stringData = someString.getBytes("UTF-8");
        data.put(stringData);
    }

    public static LoginPacket read(ByteBuffer data) {
        LoginPacker loginPacket = new LoginPacket();
        loginPacket.length = data.getShort();
        loginPacket.sessionId = data.getInt();
        loginPacket.command = data.getShort();
        loginPacket.error = data.getShort();
        loginPacket.reason = getString(data);
        return loginPacket;
    }

    public void write(ByteBuffer data) {
        data.putShort(this.length);
        data.putInt(this.sessionId);
        data.putShort(this.command);
        data.putShort(this.error);
        putString(data, this.reason);
    }
}

回答1:

I don't think you need to use AspectJ to modify your classes. I don't see what benefits using compile team weaving would add. I would suggest having your POJOs use implements Serializableand then serialize your objects using an ObjectOutputStream.

A simple example writing an object to a file:

outputStream = new ObjectOutputStream(new FileOutputStream(filePath)); 
outputStream.writeObject(yourObject);
...
// do whatever else and close stream

Similar questions:

  1. Saving to binary/serialization java
  2. Best way to store data for your game? (Images, maps, and such)