我们知道我们可以通过字符串名称
调用方法class Person {
String profile(){}
}
因此:
String method='profile'
new Person()."$method"()
然而
Class context='my.package.Person' as Class ;
new context()
不起作用
以下尝试相同:
def map=['person':my.package.Person]
new map['person']()
答案 0 :(得分:2)
你可以用同样的方式做到这一点,就像使用newInstance()
和newInstance([args...])
class Person {
String name
}
// if you hold the class already (Person is short for Person.getClass())
def p1 = Person.newInstance()
assert p1
assert p1.name==null
def p2 = Person.newInstance(name: "Duffy")
assert p2
assert p2.name=="Duffy"
// if not, load it by name (with package it would be "my.package.Person")
def p3 = Class.forName("Person").newInstance()
assert p3
或者你的上一个例子:
def map=['person':my.package.Person]
map['person'].newInstance()
map['person'].newInstance(name: "Duffy")