Bytebuddy: How to generate a native method?

Viewed 32

I have an interface

public interface Foo {
    int value();
}

I want to generate an implementation of this interface, where the method is implemented natively:

        final DynamicType.Unloaded<Foo> load = new ByteBuddy()
            .subclass(Foo.class)
            .name("FooNative")
            .initializer(new LoadedTypeInitializer() {
                @Override
                public void onLoad(final Class<?> type) {
                    System.loadLibrary("foo-native");
                }

                @Override
                public boolean isAlive() {
                    return true;
                }
            })
            .method(ElementMatchers.named("foo"))
            .intercept(/* ??? */)
            .make();

How can I generate an empty method with native modifier

@Override public native int value();

?

1 Answers

You would rather use defineMethod and add the native modifier to it. Byte Buddy will automatically detect that it's an override.

Then in the next step, you set withoutCode.

Related