更新时间:2023-12-05 15:18:58
试试这个:
def cl = Class.forName("org.package.Foo")
cl.get(1)
有点长,但应该可以工作.
A little bit longer but should work.
如果你想为静态方法创建类似switch"的代码,我建议实例化类(即使它们只有静态方法)并将实例保存在地图中.然后你可以使用
If you want to create "switch"-like code for static methods, I suggest to instantiate the classes (even if they have only static methods) and save the instances in a map. You can then use
map[name].get(1)
选择其中之一.
"$name"
是一个 GString
,因此是一个有效的语句."$name".foo()
表示调用GString
类的方法foo()
.
"$name"
is a GString
and as such a valid statement. "$name".foo()
means "call the method foo()
of the class GString
.
使用 Web 容器(如 Grails)时,您必须指定类加载器.有两种选择:
When using a web container (like Grails), you have to specify the classloader. There are two options:
Class.forName("com.acme.MyClass", true, Thread.currentThread().contextClassLoader)
或
Class.forName("com.acme.MyClass", true, getClass().classLoader)
第一个选项仅适用于 Web 上下文,第二个方法也适用于单元测试.这取决于您通常可以使用与调用 forName()
的类相同的类加载器.
The first option will work only in a web context, the second approach also works for unit tests. It depends on the fact that you can usually use the same classloader as the class which invokes forName()
.
如果你有问题,那么使用第一个选项并在你的单元测试中设置contextClassLoader
:
If you have problems, then use the first option and set the contextClassLoader
in your unit test:
def orig = Thread.currentThread().contextClassLoader
try {
Thread.currentThread().contextClassLoader = getClass().classLoader
... test ...
} finally {
Thread.currentThread().contextClassLoader = orig
}