gpt4 book ai didi

reflection - 在 Groovy 中使用 invokeMethod 动态实现接口(interface)

转载 作者:行者123 更新时间:2023-12-04 17:41:59 31 4
gpt4 key购买 nike

Groovy 提供了一些非常简洁的语言特性来处理和实现 Java 接口(interface),但我似乎有点卡住了。

我想在 Groovy 类上动态实现一个接口(interface),并使用 GroovyInterceptable.invokeMethod 拦截该接口(interface)上的所有方法调用。这是我到目前为止所尝试的:

public interface TestInterface
{
public void doBla();
public String hello(String world);
}


import groovy.lang.GroovyInterceptable;

class GormInterfaceDispatcher implements GroovyInterceptable
{
def invokeMethod(String name, args) {
System.out.println ("Beginning $name with $args")
def metaMethod = metaClass.getMetaMethod(name, args)
def result = null
if(!metaMethod)
{
// Do something cool here with the method call

}
else
result = metaMethod.invoke(this, args)
System.out.println ("Completed $name")
return result
}

TestInterface getFromClosure()
{
// This works, but how do I get the method name from here?
// I find that even more elegant than using invokeMethod
return { Object[] args -> System.out.println "An unknown method called with $args" }.asType(TestInterface.class)
}


TestInterface getThisAsInterface()
{
// I'm using asType because I won't know the interfaces
// This returns null
return this.asType(TestInterface.class)
}

public static void main(String[] args)
{
def gid = new GormInterfaceDispatcher()
TestInterface ti = gid.getFromClosure()
assert ti != null
ti.doBla() // Works
TestInterface ti2 = gid.getThisAsInterface()
assert ti2 != null // Assertion failed
ti2.doBla()
}
}

返回闭包工作正常,但我无法找到一种方法来找出在那里调用的方法的名称。

尝试对 this 引用本身进行代理(以便方法调用将调用 invokeMethod)返回 null。

最佳答案

您可以使用 Groovy 的 Map 强制功能来动态生成表示给定接口(interface)的 Map:

TestInterface getMapAsInterface() {
def map = [:]

TestInterface.class.methods.each() { method ->
map."$method.name" = { Object[] args->
println "Called method ${method.name} with ${args}"
}
}

return map.asType(TestInterface.class)
}

关于reflection - 在 Groovy 中使用 invokeMethod 动态实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1765469/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com