java - Stackoverflow 在 Map 上调用 metaClass 方法

标签 java groovy stack-overflow

这段代码导致 stackOverflow 异常:

ISerializer serializer = buildSerializer(TestDataProvider.getAuthor());
ASObject result = (ASObject) serializer.serialize();
assert result.isNotLazyProxy

此行抛出 StackOverflow:assert result.isNotLazyProxy。请注意,isNotLazyProxy 方法实际上从未被调用。

isNotLazyProxy 是一个扩展方法(在 groovy 中这些叫什么?) 定义如下:

/**
 * Asserts that this ASObject is not a lazy loaded proxy,
 * ie - that all of it's properties' values have been included
 */
ASObject.metaClass.isNotLazyProxy = { ->
    assert delegate[HibernateProxyConstants.PROXYINITIALIZED] == true
    return true;
}

但是,在该闭包的第一行设置断点表明它永远不会被调用。

相反,抛出了一个 StackOverflow:

java.lang.StackOverflowError
    at java.lang.System.arraycopy(Native Method)
    at java.lang.String.getChars(String.java:855)
    at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:391)
    at java.lang.StringBuffer.append(StringBuffer.java:224)
    at java.lang.StringBuffer.<init>(StringBuffer.java:104)
    at org.codehaus.groovy.runtime.InvokerHelper.formatMap(InvokerHelper.java:557)
    at org.codehaus.groovy.runtime.InvokerHelper.format(InvokerHelper.java:530)
    at org.codehaus.groovy.runtime.InvokerHelper.formatList(InvokerHelper.java:602)
    at org.codehaus.groovy.runtime.InvokerHelper.format(InvokerHelper.java:527)
    at org.codehaus.groovy.runtime.InvokerHelper.formatMap(InvokerHelper.java:575)

我不确定它是否相关,但 ASObjectMap 的子类,并且它的内容可能具有引用其内部其他键的属性。

我本以为这是相关的,但 StackOverflow 似乎表明 groovy 正在遍历 map 的成员。

发生什么事了?为什么会发生这种堆栈溢出?

最佳答案

assert result.isNotLazyProxy 可能没有做你想做的事情。

在 groovy 中,map.somehing 被翻译为 map.get(something)。请参阅http://groovy.codehaus.org/JN1035-Maps :

assert map2.class == null
//field syntax always refers to value of key, even if it doesn't exist
//use getClass() instead of class for maps...
assert map2.getClass() == LinkedHashMap //the kind of Map being used

因此请使用assert result.isNotLazyProxy()

当然,在您的情况下,result.isNotLazyProxy 应该返回 null,并且 assert result.isNotLazyProxy 断言应该失败。当此断言失败时,groovy 将显示断言错误,并显示图。在您的情况下,由于某种原因格式化 map 失败。

失败原因:

这是一个 known bug ,参见example 。据我所知,它与 ASObject 无关。 ,因为它不使用列表。

关于java - Stackoverflow 在 Map 上调用 metaClass 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5273605/

相关文章:

java - 从 Groovy 导入 Scala

java - 为什么调用 java.net.URLConnection.getHeaderField(0) 会导致 StackOverflowError?

java - 如何为 ANTLR 指定目标包?

java - 向android数据库中输入数据

Java父子函数调用机制关系

java - 重写 Hashtable.contains() java 时出现 StackOverflowError

c - 如何克服 Visual Studio 的堆栈大小问题(使用大数组运行 C 代码)

java - android - 生成随机日期和时间

groovy - Groovy ASTTransformation-在闭包内部执行forLoop的collectionExpression

groovy - 从 lib 目录构建的准系统 Gradle