I'm trying to create a simple class that contains static final object fields, using any byte code library. I have tried BCEL and Byte Buddy but had no success. The class I want to construct looks like this. Thanks.
public class ConstructedClass{
public static final MyClass a = new MyClass();
public static final MyClass b = new MyClass();
}
My attempt with BCEL:
ClassGen classGen=new ClassGen("org.test.lib.core", "java.lang.Object","core.java", Const.ACC_PUBLIC, null);
classGen.addEmptyConstructor(Const.ACC_PUBLIC);
ConstantPoolGen constantPoolGen=classGen.getConstantPool();
int access_flags = Const.ACC_PUBLIC | Const.ACC_STATIC | Const.ACC_FINAL;
final FieldGen FieldGen=new FieldGen( access_flags,Type.getType(Property.class), "test", constantPoolGen);
//FieldGen.setInitValue(new MyClass());
My second attempt also with BCEL:
private static final Type[] arg = {Type.getType(MyClass.class)};
InstructionList init = new InstructionList();
InstructionFactory factory=new InstructionFactory(classGen);
//init.append(new PUSH(constantPoolGen, new MyClass()));
init.append(factory.createInvoke(MyClass.class.getName(), "valueOf",
Type.getType(MyClass.class), arg, Const.INVOKESTATIC));
init.append(factory.createPutStatic("org.test.lib.core", "test", Type.getType(Property.class)));
The commented lines is where pushing my object didn't work.
With ByteBuddy You can generate a static initialization block using ByteCodeAppender. This will result in a little different class then You wanted but i think close enough:
Generation code:
Update for comment
To call a static factory method instead of constructor You just need to replace constructor call:
Multiple fields