1

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

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;
}

有没有办法排除代码重复(除了使用模板模式的子类化)?

4

2 回答 2

3

简单地说:

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());
}
于 2011-09-22T14:43:17.787 回答
2

好吧,您可以很容易地提取其中的大部分内容:

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

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

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

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

    return exceptions;
}
于 2011-09-22T14:42:17.983 回答