Search code examples
javagroovyabstract-class

Dynamically creating object instance of interface / abstract class


In Groovy or Java, assume I have an interface (or abstract class) with some unimplemented methods. I would like to generate an instance of this interface/abstract class dynamically in runtime, and have some behaviour for those unimplemented methods (e.g. based on annotation on those methods)

i.e. something like

interface Foo {
    @SomeAnnotation(...)
    foo();
}
Foo foo = someMagic(Foo.class, somethingToProvideLogicOfUnimplementedMethods);

Are there any library or technique that can achieve this?


Solution

  • In Groovy the following magic is called "Map to Interface coercion" and is available out of the box:

    import static java.lang.annotation.ElementType.METHOD
    import static java.lang.annotation.RetentionPolicy.RUNTIME
    import java.lang.annotation.Retention
    import java.lang.annotation.Target
    
    @Retention( RUNTIME )
    @Target( [ METHOD ] )
    @interface Some {
      String value() default ''
    }
    
    interface Foo {
      @Some( 'AWESOME' )
      void foo()
    }
    
    Foo magicFoo = [ foo:{->
      String annotationValue = Foo.methods.first().annotations.first().value()
      println "the $annotationValue MAGIC printed!"
    } ] as Foo
    
    assert Foo.isAssignableFrom( magicFoo.getClass() )
    
    magicFoo.foo()
    

    prints in the console:

    the AWESOME MAGIC printed!