我想從字符串的名稱派生一個groovy類的類實例。Groovy/Grails - 如何從String獲取類實例?
例如,我想要做沿着這些線路一些代碼:
def domainName
domainName = "Patient"
// but following line doesn't work, domainName is a String
def domainInstance = domainName.get(1);
我想從字符串的名稱派生一個groovy類的類實例。Groovy/Grails - 如何從String獲取類實例?
例如,我想要做沿着這些線路一些代碼:
def domainName
domainName = "Patient"
// but following line doesn't work, domainName is a String
def domainInstance = domainName.get(1);
Grails的方法是使用GrailsApplication#getArtefact。例如,
def domainInstance = grailsApplication.getArtefact("Domain",domainName)?.
getClazz()?.get(1)
這樣做,而不是Class.forName
這種方式的好處是,如果沒有域類使用該名稱,getArtefact
只是返回拋出異常的空代替。
好,
嘗試使用包
試試這個代碼來實現你的代碼:我不知道它會工作好嗎?
def domainInstance = Class.forName("Patient").newInstance()
這將工作:
Class.forName("Patient", false, Thread.currentThread().contextClassLoader).get(1)
我在找什麼,但下一個覆蓋null。不管怎麼說,還是要謝謝你! – 2010-01-13 17:45:39