【发布时间】:2019-11-13 21:26:46
【问题描述】:
我在Java中有以下方法:
public void myMethod(
@ClosureParams(
value = SimpleType.class,
options = {
"java.util.Map"
}
) Closure<String> closure
) {
...
}
其中有 @ClosureParams 来指定闭包的参数类型,用于 IDEA 中的静态类型检查和类型推断。
在 Groovy 脚本中,我这样调用这个方法:
myMethod { Map<String, Object> doc ->
...
}
而且效果很好。但是,当我尝试在我的 java 方法中为 java.util.Map 的闭包指定 通用类型 时:
public void myMethod(
@ClosureParams(
value = SimpleType.class,
options = {
"java.util.Map<java.lang.String,java.lang.Object>" // <-- added here
}
) Closure<String> closure
) {
...
}
groovy 的静态类型检查器因错误而失败:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\myproject\script.groovy: 1: Expected parameter of type java.util.Map<java.lang.String,java.lang.Object> but got java.util.Map <String, Object>
@ line 1, column 8.
myMethod { Map<String, Object> doc ->
虽然 IDEA 使用 @ClosureParams 提示推断 doc 的类型而没有任何 Map 或 Map<...>。
当我查看groovy.transform.stc.SimpleType 类的源代码时,我发现这个类没有指定泛型类型的能力,因为它使用普通的Class.forName:
public class SimpleType extends SingleSignatureClosureHint {
@Override
public ClassNode[] getParameterTypes(final MethodNode node, final String[] options, final SourceUnit sourceUnit, final CompilationUnit unit, final ASTNode usage) {
ClassNode[] result = new ClassNode[options.length];
for (int i = 0; i < result.length; i++) {
result[i] = findClassNode(sourceUnit, unit, options[i]);
}
return result;
}
}
// findClassNode method:
protected ClassNode findClassNode(final SourceUnit sourceUnit, final CompilationUnit compilationUnit, final String className) {
if (className.endsWith("[]")) {
return findClassNode(sourceUnit, compilationUnit, className.substring(0, className.length() - 2)).makeArray();
}
ClassNode cn = compilationUnit.getClassNode(className);
if (cn == null) {
try {
cn = ClassHelper.make(Class.forName(className, false, sourceUnit.getClassLoader()));
} catch (ClassNotFoundException e) {
cn = ClassHelper.make(className);
}
}
return cn;
}
我的问题:如何在 groovy 中使用泛型指定闭包参数类型?最好有 IDEA 的支持。
【问题讨论】: