我在我的代码库中有这两种方法,我想以某种方式合并以避免代码重复:
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;
}
有没有办法分解代码重复(除了使用带有模板模式的子类)?
答案 0 :(得分: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());
}
答案 1 :(得分: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;
}