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

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

Dynamically creating object instance of interface / abstract class

问题

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

即,类似于

interface Foo {
    @SomeAnnotation(...)
    foo();
}
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

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

Are there any library or technique that can achieve this?

答案1

得分: 4

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

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()

在控制台中输出:

the AWESOME MAGIC printed!
英文:

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!

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:

确定