Details
-
Type:
Sub-task
-
Status:
Open
-
Priority:
Major
-
Resolution: Unresolved
-
Affects Version/s: 1.7.1
-
Fix Version/s: None
-
Component/s: groovy-jdk
-
Labels:None
-
Environment:Windows, Groovy 1.7.1
-
Testcase included:yes
-
Number of attachments :
Description
If i define methods with same name and parameters on a class, one as static other as instance method, the order becomes important.
Try this in the groovy console:
class IDoNothing {
}
IDoNothing.metaClass.sayHello = {
println "Instance says hello"
}
IDoNothing.metaClass.static.sayHello = {
println "Class says hello"
}
def idn = new IDoNothing()
IDoNothing.sayHello()
idn.sayHello()
It will print:
Class says hello
Class says hello
although the second sayHello() was called on an instance. If you define the static method first, all works as expected:
class IDoNothing {
}
IDoNothing.metaClass.static.sayHello = {
println "Class says hello"
}
IDoNothing.metaClass.sayHello = {
println "Instance says hello"
}
def idn = new IDoNothing()
IDoNothing.sayHello()
idn.sayHello()
Output:
Class says hello
Instance says hello
I am not sure this is a bug - though it may not be the behavior you expect. And you are certainly welcome to discuss the merits of alternative behavior to the existing one.
Java doesn't let you define a method or field at both instance and static scopes. Groovy does when using EMC but new definitions override previous ones. In your example, you only ever define one method that is visible from a static context so the behavior calling from a static context doesn't change. The added static method however is visible at both the static and instance levels, so whichever you define last becomes the one instances will use. I think a case could certainly be mounted that Groovy could better distinguish between the static and instance cases and use that knowledge when selecting methods, but perhaps an even stronger case could be mounted not to use static and instance methods with the same names and same parameters.