如何在任何字节码库中创建具有最终静态字段的类?

时间:2017-12-19 12:56:14

标签: java bytecode byte-buddy bcel

我正在尝试使用任何字节代码库创建一个包含静态最终对象字段的简单类。我曾尝试过BCEL和Byte Buddy但没有成功。我想要构建的类看起来像这样。感谢。

public class ConstructedClass{

   public static final MyClass a = new MyClass();

   public static final MyClass b = new MyClass(); 
}

我对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());

我对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))); 

注释行是推送我的对象不起作用的地方。

1 个答案:

答案 0 :(得分:2)

使用ByteBuddy您可以使用ByteCodeAppender生成静态初始化块。这会导致你想要一个不同的课程,但我认为足够接近:

public class ConstructedClass {

   public static final MyClass a;

   static {
        a = new MyClass();
   } 
}

代码:

public class ByteBuddyTest {

    public static void main(String[] args) throws Exception {
        DynamicType.Loaded loaded =
            new ByteBuddy()
            .subclass(Object.class)
                .initializer( new ByteCodeAppender() {
                    @Override public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext,
                                                MethodDescription instrumentedMethod) {
                        StackManipulation.Size size = new StackManipulation.Compound(
                            TypeCreation.of(new TypeDescription.ForLoadedType(MyClass.class)),
                            Duplication.SINGLE,
                            MethodInvocation.invoke(new TypeDescription.ForLoadedType(MyClass.class).getDeclaredMethods().filter(ElementMatchers.isDefaultConstructor()).getOnly()),
                            FieldAccess.forField(implementationContext.getInstrumentedType().getDeclaredFields().filter(ElementMatchers.named("a")).getOnly()).write()
                        ).apply(methodVisitor, implementationContext);

                        return new Size(size.getMaximalSize(), instrumentedMethod.getStackSize());
                    }
                })
            .name("org.test.lib.core.ConstructedClass")
            .modifiers(Opcodes.ACC_PUBLIC)
            .defineField("a", MyClass.class, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL)
            .make()
            .load(ByteBuddyTest.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION);

        Object obj = loaded.getLoaded().getConstructor().newInstance();
        System.out.println(obj.getClass().getField("a").get(obj));
    }

    public static class MyClass {
        public MyClass(String arg) {}

        public static MyClass createMyClass(String arg) {
            return new MyClass(arg);
        }
    }
}

更新评论

调用静态工厂方法而不是构造函数您只需要替换构造函数调用:

StackManipulation.Size size = new StackManipulation.Compound(
    new TextConstant("test"),
    MethodInvocation.invoke(new TypeDescription.ForLoadedType(MyClass.class).getDeclaredMethods().filter(ElementMatchers.named("createMyClass")).getOnly()),
         FieldAccess.forField(implementationContext.getInstrumentedType().getDeclaredFields().filter(ElementMatchers.named("a")).getOnly()).write()
).apply(methodVisitor, implementationContext);

多个字段

    DynamicType.Builder builder = new ByteBuddy().subclass(Object.class);
    List<String> fields = Lists.newArrayList("a", "b", "c");

    for (String str : fields) {
        builder = builder.defineField(str, MyClass.class, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL);
    }

    DynamicType.Loaded loaded = builder.make().load(ByteBuddyTest.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION);

    Object obj = loaded.getLoaded().getConstructor().newInstance();
    System.out.println(obj.getClass().getField("a"));
    System.out.println(obj.getClass().getField("c"));