有人可以告诉我是否有可能通过执行以下操作来减少我班级中的方法数量,使2个类成为1:
public void duplicateEntries(String personName, String entryType) throws CustomException
{
for (Entry entry : allEntries)
{
if ( entry instanceof entryType)
{
if (personName.equalsIgnoreCase(entry.getName()))
{
throw new CustomException("\nAn entry for " +
personName + "already exists. Entry has been cancelled.");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译时,编译器报告"无法找到符号 - entryType":
if ( entry instanceof entryType)
Run Code Online (Sandbox Code Playgroud)
原始代码:
public void duplicatePersonal(String personName) throws CustomException
{
for (Entry entry : allEntries)
{
if ( entry instanceof Personal)
{
if (personName.equalsIgnoreCase(entry.getName()))
{
throw new CustomException("\nAn entry for " +
personName + "already exists. Entry has been cancelled.");
}
}
}
}
public void duplicateBusiness(String personName) throws CustomException
{
for (Entry entry : allEntries)
{
if ( entry instanceof Business)
{
if (personName.equalsIgnoreCase(entry.getName()))
{
throw new CustomException("\nAn entry for " +
personName + "already exists. Entry has been cancelled.");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道它不会减少我的代码,但有一些像这样的方法我也可以应用它.
你为什么不传递你想要找到重复的东西的类型?
它可能是这样的
public boolean hasDuplicates(String name, Class type) {
for (Entry entry : allEntries) {
if (type.isInstance(entry) && name.equalsIgnoreCase(entry.getName())) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我不会依赖于抛出一个Exception如果找到重复,因为如果你正在寻找重复,那么这意味着可能有重复,所以它不是那么特殊:D
当然我不知道你使用的是什么,也许传球Object type并不是那么好,但是在你写完这篇文章之后你总能提出一个更好的解决方案.
你会像下面这样使用它:
if (hasDuplicates(name, Personal.class)) {
// handle duplicates
}
Run Code Online (Sandbox Code Playgroud)