我有一個.getProperties()
方法的Java類,但調用在Groovy該方法時,它返回屬性的LinkedHashMap
,從Groovy Beans magic代替的GetProperties方法我的Java類定義。如何調用可變參數的Java方法命名的GetProperties()是Groovy的覆蓋
如何調用我的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的問題,我相信它是。
我的歉意,我沒有測試我的測試用例。這個問題實際上是以一種可變方法產生的。看我更新的例子。 – Andrew