2017-05-31 39 views
1

我需要計算特定的對象,但我只知道在運行時哪個對象。 現在我有這樣的事情如何計算在運行時選擇的類型「對象」

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種不同的類型,我總是隻需要其中的一種。 基本上我想打電話給基於字符串

+0

你能否解釋多一點你要實現的目標是什麼?你會有多少種不同的類型? 10?成千上萬的?你會每個類型有一個字段嗎?你是否曾經想要一個複合'Details',比如「需要多少個對象」,需要兩個'Type1'和四個'Type3'?儘管你的問題很模糊,但可能會被視爲「太寬泛」或「不清楚」。 – AJNeufeld

+0

不要將字符串與'=='進行比較。使用'.equals'。退房[如何比較字符串](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) –

+0

@AJNeufeld我添加了一些信息,我不認爲我可以比這更具體 – Champ

回答

1

Container類可能包含一個Map它的列表:

class Container { 
    private Map<String, List<?>> lists = new HashMap<>(); 

    private List<TypeOne> first = ...; 
    private List<TypeTwo> second = ...; 

    public Container() { 
     lists.put("type1", first); 
     lists.put("type2", second); 
    } 

    public int count(String type) { 
     return lists.get(type).size(); 
    } 
} 

你可以抓住致電count基於該類型的大小:

public boolean hasNumberOfObjectRequired() { 
    String type = details.getTypeOfObjectRequired(); 
    int requiredCount = details.getNumberOfObjectRequired(); 

    return container.count(type) >= requiredCount; 
} 
+0

感謝您的幫助!我也喜歡lambdas的解決方案,它可以幫助我熟悉函數式編程 – Champ

0

您可以使用反射不同的方法......

public boolean hasNumberOfObjectRequired() { 
int count = 0; 
String type = details.getTypeOfObjectRequired(); 
Method m = Container.class.getMethod("countType"+type.charAt(4)); 
return m.invoke(container) > details.getNumberOfObJectRequired); 
} 

或者,如果類型是INT你可以使用一個開關

switch(type){ 
case "type1": 
count = ... 
break; 
case "type2" 
.... 
} 

更妙而不是字符串

+0

這是如何更好?似乎是不必要的反射使用 –

+0

反射似乎有點矯枉過正,我不知道它是否真的更好..連接如果和開關是相同的東西,所以問題仍然存在 – Champ

+0

我剛纔展示了一些可能的解決方案。我知道在這種情況下反射是不必要的,但它也比原來的靜態解決方案更好。如果你有更好的,請告訴我們 –