我不知道这是错误还是功能,但是对于具有 Java 背景的人来说,跟踪异常原因绝对是不直观的。
即使变量未定义,Groovy 也允许引用变量。
例如考虑以下类:
class B {
def infos;
public B(String param)
{
infos = param
}
public getInfo()
{
return info;
}
}
如果你注意到了,里面
getInfo()
, 我回来了 info
这是从未定义的。但是,Eclipse 不会给出警告。所以我继续写以下内容:class A
{
static main(def args)
{
B bObj = new B("Mahesh")
println "Hello groovy"
println bObj.getInfo()
println "Hello groovy"
}
}
现在这给
StackOverflowError
具有巨大的堆栈跟踪:Exception in thread "main" java.lang.StackOverflowError
at java.lang.Exception.<init>(Exception.java:102)
at java.lang.ReflectiveOperationException.<init>(ReflectiveOperationException.java:89)
at java.lang.reflect.InvocationTargetException.<init>(InvocationTargetException.java:72)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at groovy.lang.MetaClassImpl$GetBeanMethodMetaProperty.getProperty(MetaClassImpl.java:3493)
at org.codehaus.groovy.runtime.callsite.GetEffectivePogoPropertySite.callGroovyObjectGetProperty(GetEffectivePogoPropertySite.java:67)
--> at packages.B.getInfo(ThreadDumpsExp.groovy:169) <--
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at groovy.lang.MetaClassImpl$GetBeanMethodMetaProperty.getProperty(MetaClassImpl.java:3493)
at org.codehaus.groovy.runtime.callsite.GetEffectivePogoPropertySite.callGroovyObjectGetProperty(GetEffectivePogoPropertySite.java:67)
:
:
这里的堆栈跟踪没问题,因为在堆栈跟踪的某个地方,它指向了我在上面的堆栈跟踪中用箭头突出显示的特定行。我期待堆栈跟踪中的这一行,这就是为什么我能够快速跟踪它。当今天我在我的项目中遇到同样的问题时,问题就出现了。堆栈跟踪同样巨大。我不知道它实际上哪里出了问题,所以我无法猜测哪条线路实际上可能有问题。最糟糕的是在调试期间停止在 Groovy 的源代码中。我不得不在不同的地方反复放置断点以实际停止在它们处的执行。一段时间后,我在我的代码中找到了调试器实际停止的那一行。从那里我逐步浏览我的整个代码以找到导致问题的行。那行是一个简单的 getter,它返回了错误的东西。
现在我知道我在编写代码时应该更加清醒,不应该犯从 getter 返回一个不存在的变量的错误。但是有没有办法让它不做上面所做的事情?
编辑
同样在添加
@TypeChecked
之后,出现以下错误。它早些时候正常工作。最佳答案
为属性添加getter时,无论该属性是否存在,都需要使用.@
来引用该属性。运算符(operator)。这是直接字段访问运算符,它跳过任何 getter 并直接访问属性。如果您不使用该运算符,则会一遍又一遍地调用相同的 getter,直到您得到 StackOverflowError
.
例如:
def getInfo() {
return this.@info
}
请参阅 Groovy operator docs 中的第 6.2 节直接字段访问运算符多一点。
关于groovy - 不正确的 getter 的 groovy 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33102259/