如何调用Groovy覆盖的名为getProperties()的可变参数Java方法

我有一个带有.getProperties()方法的
Java类,但是当在Groovy中调用该方法时,它从
Groovy Beans magic而不是我的Java类定义的getProperties方法返回属性的LinkedHashMap.

如何调用我的getProperties()方法而不是Groovy方法?

我的Java代码(简化):

import java.util.*;

public class MyObject {
    private Collection<Property> properties;

    private static class Property {
        public String value;

        public Property(String value) {
            this.value = value;
        }

        public String toString() {
            return String.format("Property: %s", this.value);
        }
    }

    private static interface PropertyFilter {
        boolean passes(String value);
    }

    public static class StartsWithPropertyFilter implements PropertyFilter {
        public String prefix;

        public StartsWithPropertyFilter(String prefix) {
            this.prefix = prefix;
        }

        public boolean passes(String value) {
            if(value == null)
                return false;
            return value.startsWith(prefix);
        }
    }

    public MyObject() {
        this(new ArrayList<Property>());
    }

    public MyObject(Collection<Property> myProperties) {
        this.properties = myProperties;
    }

    public void addProperty(String value) {
        this.properties.add(new Property(value));
    }

    public Collection<Property> getProperties(PropertyFilter... filters) {
        Collection<Property> ret = new ArrayList<Property>();
        for(Property prop : properties) {
            boolean passes = true;
            for(PropertyFilter filter : filters) {
                if(!filter.passes(prop.value)) {
                    passes = false;
                    break;
                }
            }
            if(passes) {
                ret.add(prop);
            }
        }
        System.out.println("Java getProperties()");
        return ret;
    }

    public static void main(String[] args) {
        MyObject obj = new MyObject();
        obj.addProperty("Fast");
        obj.addProperty("Strong");
        obj.addProperty("Furious");
        System.out.println(obj.getProperties());
        System.out.println(obj.getProperties(new MyObject.StartsWithPropertyFilter("F")));
    }
}

我的Groovy代码:

MyObject obj = new MyObject()
obj.addProperty("Fast")
obj.addProperty("Strong")
obj.addProperty("Furious")
println obj.getProperties()
println obj.getProperties(new MyObject.StartsWithPropertyFilter("F"))

用这个运行:

javac MyObject.java && groovy Run.groovy && echo && java MyObject

我得到这个输出:

[class:class MyObject]
Java getProperties()
[Property: Fast, Property: Furious]

Java getProperties()
[Property: Fast, Property: Strong, Property: Furious]
Java getProperties()
[Property: Fast, Property: Furious]

我的Groovy版本是一个非常新的版本(2.0.1):

$groovy -version
Groovy Version: 2.0.1 JVM: 1.6.0_27 Vendor: Sun Microsystems Inc. OS: Linux

但我最初在1.8.5看到了这个问题,我相信它是.

最佳答案 这可能不再相关,但只需稍作修改即可:

obj.getProperties([] as MyObject.PropertyFilter[])

更改是PropertyFilter接口不能是私有的.

点赞