我的代码库中有这两种方法,我想以某种方式合并它们以避免代码重复:
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/