我需要計算特定的對象,但我只知道在運行時哪個對象。 現在我有這樣的事情如何計算在運行時選擇的類型「對象」
public class Details {
private String typeOfObjectRequired;
private int numberOfObjectRequired;
}
而在另一個類我有
public class Container {
private List<Type1> type1List;
private List<Type2> type2List;
private Type3 type3Object;
public int countType1() {
return type1List.size();
}
public int countType2() {
return type2List.size();
}
public int countType3() {
return type3Object.getNumberOfSomething();
}
}
我現在做這樣的(在同時具有細節和容器作爲屬性的三等)
public boolean hasNumberOfObjectRequired() {
int count = 0;
String type = details.getTypeOfObjectRequired();
if(type.equals("type1")) count = container.countType1();
else if (type.equals("type2")) count = container.countType2();
else if (type.equals("type3")) count = container.countType3();
if (count > details.getNumberOfObJectRequired) return true;
return false;
}
有沒有更好的方法來做到這一點?如果我不喜歡這麼多,也因爲我不只有3種不同的類型。
編輯: 現在我有5種不同的類型,我總是隻需要其中的一種。 基本上我想打電話給基於字符串
你能否解釋多一點你要實現的目標是什麼?你會有多少種不同的類型? 10?成千上萬的?你會每個類型有一個字段嗎?你是否曾經想要一個複合'Details',比如「需要多少個對象」,需要兩個'Type1'和四個'Type3'?儘管你的問題很模糊,但可能會被視爲「太寬泛」或「不清楚」。 – AJNeufeld
不要將字符串與'=='進行比較。使用'.equals'。退房[如何比較字符串](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) –
@AJNeufeld我添加了一些信息,我不認爲我可以比這更具體 – Champ