Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading