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

标签 java groovy method-signature

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

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
}

谢谢:)

最佳答案

您的问题中没有什么特别的常规问题,更多的是关于编译/运行时失败。

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

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

关于java - 确保正确参数类型的 Groovy 最佳/推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35118401/

相关文章:

scala - Groovy 的安全取消引用运算符 (?.) 的最佳 Scala 模仿?

java - 在 Grails 应用程序中使用 Java 代码导致编译永无止境循环

java - 为什么我得到 "onCreate(Bundle) already defined"?

Java IndexOutOfBoundsException

java - hibernate ,JDBC : Error calling Driver#connect

java - 在 SugarORM 中将对象作为参数传递

vb.net - 委托(delegate)和 ParamArray - 解决方法建议?

java - 通用类型不匹配

groovy - GroovyTestCase 方法必须返回 void 吗?

c++ - 用 foo(T) 替换模板函数 foo(T*)