java - Method 和 Constructor<?> 都继承自 Member,都具有 getExceptionTypes() 方法。在这种情况下如何避免代码重复?

标签 java oop refactoring code-duplication

我的代码库中有这两种方法,我想以某种方式合并它们以避免代码重复:

protected IJavaType[] getExceptionTypes(Method method) {
    Class<?>[] declaredExceptions = method.getExceptionTypes();

    IJavaType[] exceptions = new IJavaType[declaredExceptions.length];

    for (int i = 0; i < declaredExceptions.length; i++) {
        exceptions[i] = getType(declaredExceptions[i]);
    }

    return exceptions;
}

protected IJavaType[] getExceptionTypes(Constructor<?> c) {
    Class<?>[] declaredExceptions = c.getExceptionTypes();

    IJavaType[] exceptions = new IJavaType[declaredExceptions.length];

    for (int i = 0; i < declaredExceptions.length; i++) {
        exceptions[i] = getType(declaredExceptions[i]);
    }

    return exceptions;
}

有什么方法可以排除代码重复(除了使用带有模板模式的子类之外)?

最佳答案

简单的怎么样:

private IJavaType[] getExceptionTypes(Class<?>[] declaredExceptions) {
    IJavaType[] exceptions = new IJavaType[declaredExceptions.length];

    for (int i = 0; i < declaredExceptions.length; i++) {
        exceptions[i] = getType(declaredExceptions[i]);
    }

    return exceptions;
}

protected IJavaType[] getExceptionTypes(Method method) {
    return getExceptionTypes(method.getExceptionTypes());
}

protected IJavaType[] getExceptionTypes(Constructor<?> c) {
    return getExceptionTypes(c.getExceptionTypes());
}

关于java - Method 和 Constructor<?> 都继承自 Member,都具有 getExceptionTypes() 方法。在这种情况下如何避免代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7516650/

相关文章:

c# - C#中的Delphi类

oop - 与面向对象设计相关的组合是什么?

clojure:在 "if"中删除重复的惯用方法?

java - 在 tomcat 上部署为 WAR 的 Spring boot REST 应用程序无法正常工作

java - Collection 抛出或不抛出 ConcurrentModificationException 基于 Collection 的内容

java - 如何自动调用方法来停止线程?

php - 重构我的表单的最佳方法(面向 oop 的程序?)

java - 如何为方法的所有错误或空参数设置默认值?

java - 连接网络中的两个客户端

java - 从 Tomcat 6 CometProcessor 中写入是非阻塞的