gpt4 book ai didi

java - Groovy:如何调用带注释的方法

转载 作者:行者123 更新时间:2023-11-30 03:37:40 24 4
gpt4 key购买 nike

我在几个类中的某些方法的顶部粘贴了一个注释@MyAnnotation,如下所示:

FirstClass {
@MyAnnotation
doSomethingWith(String text) { println 'text from first class' }

@MyAnnotation
doSomethingWith(Foo foo) { println 'foo from first class' }

@MyAnnotation
doAlsoSomethingWith(Bar bar) { println 'bar from first class' }
}

SecondClass {
@MyAnnotation
doOtherStuffWith(Foo foo) { println 'foo from second class' }
}

GenericGateway {
execute(instancedParam) {
// call something passing an instance of "Foo" class
// call something passing an instance of "Bar" class
// call something passing an instance of "String" class
}
}

现在我期望每个用 @MyAnnotation 注释的方法和相同方法的参数(不关心方法的名称 self)在运行时根据实例化参数从“网关”调用。

// Example:

gateway.execute(new Foo(...))
gateway.execute('something')
gateway.execute(new Bar(...))

// I am expecting to see:

foo from first class
foo from second class
text from first class
bar from first class

如果我要用 Java 来解决这个问题,我可能最终会使用“反射”API 并通过某种策略将方法名称映射到某个地方。有没有办法用 Groovy 做得更“优雅”?

最佳答案

我不知道有什么捷径可以简化 Java 的反射 API。但您始终可以从 Groovy 的简洁性中受益:

import java.lang.reflection.*
import java.lang.annotation.*

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface A {}

class Annotated {
@A def a() { "a" }
@A def b() { "b" }
def c() { "c" }
}

ann = new Annotated()

methods = ann.class.methods.findAll { it.getAnnotation(A) }

assert methods.size() == 2

assert methods.collect { it.invoke(ann) } == ["a", "b"]

关于java - Groovy:如何调用带注释的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27469305/

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