我想在数据库中存储某种东西应该是字符串还是整数。我的幻想是这样的:
Class FantasyClass{
String someInfo
Class whichClass
}
然后我可以这样称呼它:
def thisThing = new FantasyClass(someInfo:'lalala',whichClass:String)
有没有解决此功能的方法?
我可以去的地方:
def getAThing = FantasyClass.get(1)
assert getAThing.whichClass == String
assert 'thisIsAString' instanceof getAThing.whichClass //THIS IS WHAT I REALLLLLLY WANT!!!
最佳答案
您可以使用asType
方法
def getAThing = FantasyClass.get(1)
assert getAThing.whichClass == String
assert 'thisIsAString'.getClass() == getAThing.someInfo.asType(getAThing.whichClass)
这是一个更通用的示例:
def value = 123
def otherThing = new FantasyClass(
someInfo: value.toString(),
whichClass: value.getClass()).save()
assert otherThing.someInfo.asType(getAThing.whichClass) instanceof Integer
您可以在域类中添加一个辅助方法,该方法将为您将String转换为指定的类型:
def getTypedValue() {
someInfo?.asType(foo)
}
然后您可以执行以下操作:
assert otherThing.typedValue == 123
关于class - Grails:将类文字存储在数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9590686/