Generate code that calls static method from another class and uses several fields as arguments

Viewed 79

I've been struggling for a while trying to find a solution to this problem. Hope you can help me out.

I'm trying to generate a method that calls a static method from another class using some already defined fields:

class Test {
   private String someField;
   private String otherField;
}

Expected result:

class Test {
   private String someField;
   private String otherField;

   public String getCacheKey() {
      return SimpleCacheKey.of(this.someField, this.otherField);
   }
}

class SimpleCacheKey {
    public static String of(final Object... values) {
        // Some Operations
        return computed_string;
    }
}

I've tried several things, closest one:

public class ModelProcessor implements Plugin {
    @Override
    public Builder<?> apply(final Builder<?> builder,
                            final TypeDescription typeDescription,
                            final ClassFileLocator classFileLocator) {

        return builder.defineMethod("getCacheKey", String.class, Visibility.PUBLIC)
                .intercept(new SimpleCacheKeyImplementation());
    }

    @Override
    public void close() throws IOException {

    }

    @Override
    public boolean matches(final TypeDescription typeDefinitions) {
        return true;
    }
}

public class SimpleCacheKeyImplementation implements Implementation {
    private static final MethodDescription SIMPLE_CACHE_KEY_OF = getOf();

    @SneakyThrows
    private static MethodDescription.ForLoadedMethod getOf() {
        return new MethodDescription.ForLoadedMethod(SimpleCacheKey.class.getDeclaredMethod("of", Object[].class));
    }

    @Override
    public InstrumentedType prepare(final InstrumentedType instrumentedType) {
        return instrumentedType;
    }

    @Override
    public ByteCodeAppender appender(final Target implementationTarget) {
        final TypeDescription thisType = implementationTarget.getInstrumentedType();

        return new ByteCodeAppender.Simple(Arrays.asList(
                // first param
                MethodVariableAccess.loadThis(),
                this.getField(thisType, "someField"),

                // second param
                MethodVariableAccess.loadThis(),
                this.getField(thisType, "otherField"),

                // call of and return the result
                MethodInvocation.invoke(SIMPLE_CACHE_KEY_OF),
                MethodReturn.of(TypeDescription.STRING)
        ));
    }

    private StackManipulation getField(final TypeDescription thisType, final String name) {
        return FieldAccess.forField(thisType.getDeclaredFields()
                .filter(ElementMatchers.named(name))
                .getOnly()
        ).read();
    }
}

However, generated code is as follows (decompiled with Intellij Idea):

public String getCacheKey() {
        String var10000 = this.name;
        return SimpleCacheKey.of(this.someValue);
    }

Changing the signature of SimpleCacheKey.of and trying to workaround the problem with a List is not an option.

1 Answers

You are calling a vararg method, java bytecode doesnt have that. So you need to create an actual array of the correct type to call the method.

@Override
public ByteCodeAppender appender(final Target implementationTarget) {
    final TypeDescription thisType = implementationTarget.getInstrumentedType();

    return new ByteCodeAppender.Simple(Arrays.asList(ArrayFactory.forType(TypeDescription.Generic.OBJECT)
            .withValues(Arrays.asList( //
                    new StackManipulation.Compound(MethodVariableAccess.loadThis(),
                            this.getField(thisType, "field1")),
                    new StackManipulation.Compound(MethodVariableAccess.loadThis(),
                            this.getField(thisType, "field2")))
            ), MethodInvocation.invoke(SIMPLE_CACHE_KEY_OF) //
            , MethodReturn.of(TypeDescription.STRING)));

}

Maybe byte-buddy has a special builder for that, but at least thats one way of doing that.

Imo: it is often a good approach to write a java version of the bytecode you want to generate. That way you can compare the javac bytecode and bytebuddy bytecode.

Related