我目前正在将具有方法的旧式Groovy类转换为Java,并且对于大多数方法而言,只需稍加修改即可轻松实现。 现在,我陷入了将闭包作为参数的方法:
transformer.renameNumbers([:], { Number->
return "${number.name}@somecompany.com"
})
}
renameNumbers
实现是:
renameNumbers(Map<String,String> renameMap, someclosure = {it}) {
numbers.each { it->
if(newUsername == null ) {
newNumbername = someclosure.call(it)
}
if(newNumbername!=null && newNumbername!=it.number) {
def oldNumber= it.number
it.number = newNumbername
log.info("Changed numbername key of from '$oldNumber' to '$newNumbername'")
}
}
问题是,如果我尝试简单地通过:transformer.renameNumbers(Map, Object)
它抱怨:
groovy.lang.MissingMethodException: No signature of method: org.eclipse.emf.ecore.util.EObjectContainmen.call() is applicable for argument types:
我猜这是因为我的普通Java对象没有call()方法。 有办法避免这种情况吗?例如,如果我使用自定义调用方法创建自定义Java类?
谢谢
答案 0 :(得分:0)
您可以尝试使用Java 8s 功能接口,例如Function<T,R>
和Lambdas:
//Function<Number, String> f = (n) -> n.name + "@somecompany.com";
transformer.renameNumbers(new HashMap<>(), (n) -> n.name + "@somecompany.com");
用法:
void renameNumbers(Map<String, String> renameMap, Function<Number, String> somefunction) {
numbers.forEach(it -> {
String newNumbername = somefunction.apply(it); // <-----
if (newNumbername != null && newNumbername != it.number) {
String oldNumber = it.number;
it.number = newNumbername;
log.info("Changed numbername key of from '" + oldNumber + "' to '" + newNumbername + "'");
}
});
}