Thursday, July 10, 2014

Lambda annotations

I am still startled by Java. While playing with Byte Buddy I noodled with adding annotations to a class at runtime. I wrote this:

final Class<? extends X> dynamicType
            = (Class<< extends X>) new ByteBuddy().
        subclass(Object.class).
        implement(X.class).
        annotateType(() -> Inject.class).
        method(named("toString")).intercept(value("Hello World!")).
        method(named("foo")).intercept(value(3)).
        make().
        load(ByteBuddyMain.class.getClassLoader(), WRAPPER).
        getLoaded();

Get a load of "annotatedType"! It wants an annotation instance. Originally I tried:

new Inject() {
    @Override
    public Class<Inject> annotationType() {
        return Inject.class;
    }
}

What the hey, then I thought to try the lambda expression and live dangerously. It works!

Post a Comment