动态创建接口/抽象类的对象实例。

huangapple go评论95阅读模式
英文:

Dynamically creating object instance of interface / abstract class

问题

In Groovy or Java, 假设我有一个带有一些未实现方法的接口(或抽象类)。 我想在运行时动态生成该接口/抽象类的实例,并为这些未实现的方法提供一些行为(例如,基于这些方法上的注解)。

即,类似于

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

是否有任何库或技术可以实现这一目标?

英文:

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

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

Are there any library or technique that can achieve this?

答案1

得分: 4

在Groovy中,以下的魔法被称为“Map to Interface coercion”,并且可以直接使用:

  1. import static java.lang.annotation.ElementType.METHOD
  2. import static java.lang.annotation.RetentionPolicy.RUNTIME
  3. import java.lang.annotation.Retention
  4. import java.lang.annotation.Target
  5. @Retention( RUNTIME )
  6. @Target( [ METHOD ] )
  7. @interface Some {
  8. String value() default ''
  9. }
  10. interface Foo {
  11. @Some( 'AWESOME' )
  12. void foo()
  13. }
  14. Foo magicFoo = [ foo:{->
  15. String annotationValue = Foo.methods.first().annotations.first().value()
  16. println "the $annotationValue MAGIC printed!"
  17. } ] as Foo
  18. assert Foo.isAssignableFrom( magicFoo.getClass() )
  19. magicFoo.foo()

在控制台中输出:

  1. the AWESOME MAGIC printed!
英文:

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

  1. import static java.lang.annotation.ElementType.METHOD
  2. import static java.lang.annotation.RetentionPolicy.RUNTIME
  3. import java.lang.annotation.Retention
  4. import java.lang.annotation.Target
  5. @Retention( RUNTIME )
  6. @Target( [ METHOD ] )
  7. @interface Some {
  8. String value() default ''
  9. }
  10. interface Foo {
  11. @Some( 'AWESOME' )
  12. void foo()
  13. }
  14. Foo magicFoo = [ foo:{->
  15. String annotationValue = Foo.methods.first().annotations.first().value()
  16. println "the $annotationValue MAGIC printed!"
  17. } ] as Foo
  18. assert Foo.isAssignableFrom( magicFoo.getClass() )
  19. magicFoo.foo()

prints in the console:

  1. the AWESOME MAGIC printed!

huangapple
  • 本文由 发表于 2023年5月11日 19:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定