英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论