开发者

Groovy AST Transformations - How can I figure out the return type of a MethodCallExpression?

开发者 https://www.devze.com 2023-01-31 18:41 出处:网络
With Groovy AST Transformations, how can I figure out the return type 开发者_如何学Pythonof a MethodCallExpression?

With Groovy AST Transformations, how can I figure out the return type 开发者_如何学Pythonof a MethodCallExpression?

MethodCallExpression.getType() always returns java.lang.Object even if I explicitly define the return type of the method in the method definition.


Due to the dynamic nature of groovy, the AST can't know the return type of a method call expression at compile time. For example:

class Example {
    String foo() { "foo" }
}
def e = new Example()
assert e.foo() == "foo"

Looks simple enough. foo returns a string, so the MethodCallExpression for e.foo() should have a type of String, right? But what if foo is changed in the metaClass?

class Example {
    String foo() { "foo" }
}
def e = new Example()
if (someRuntimeCondition) {
    e.metaClass.foo = { -> 42 }
}
assert e.foo() == "foo"  // is foo a String or an Int?

The groovy compiler just doesn't have enough information to make any assumptions about the method call since it could change at runtime, so it has to compile it down to an Object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号