Groovy最佳/推荐方法,以确保正确的参数类型

时间:2016-01-31 19:31:55

标签: java groovy method-signature

我正在努力以最好的“Groovy-way”做事。 检查参数类型(关于性能和“Groovy-way”)的最佳方法是什么?我有两个实现:

def deploy(json) {
    if (!(json instanceof String) && (json instanceof File)) {
        json = json.text
    } else {
        throw new IllegalArgumentException('argument type mismatch – \'json\' should be String or File')
    }
    // TODO
}

def deploy(File json) {
    deploy(json.text)
}

def deploy(String json) {
    // TODO
}

谢谢:)

2 个答案:

答案 0 :(得分:4)

在你的问题中没有任何特定的groovy,更多的是编译/运行时失败。

在第一个代码段json变量中有Object类型并允许传入所有内容。如果您错误地传入JSON对象或Map,它将在运行时失败

在第二个片段中,json被限制为FileString。我更喜欢它。

答案 1 :(得分:1)

instanceof检查应该没问题。但是我认为你的情况是错的 - 似乎你想做:

if (json instanceof File) {
    json = json.text
} else if(!(json instanceof String)) {
    throw new IllegalArgumentException('argument type mismatch – \'json\' should be String or File')
}

您还可以撰写以下内容:

if (json.class in [String.class, File.class]) {

您的第二种方法看起来更简单,只有两种方法可以通过签名清楚地显示意图。

相关问题