2016-11-19 28 views
-1

我有一個Class被稱爲Mineral和其他類擴展這一個,如Gold,IronCoalSwitch a SuperClass

我想開關一個Mineral,以找出哪些礦物一直通過以下addMineral方法傳遞

public List<Mineral> addMineral(Mineral mineral, int amount){ 
    switch (mineral){ 
     case Gold: 
      break; 
    } 
} 

但我不知道如何插入擴展Mineral的類作爲例子。事實上上面的例子不起作用。

這是可以實現的嗎?這是正確的方式還是有更好的解決方案?

+1

不能使用對象使用開關,除了字符串。這種補充將在未來通過模式匹配提供給Java。看到這裏:(https://youtu.be/e9eSPtpiGkA) – Logan

+0

'if(Mineral instanceof Gold){...} else if(Mineral instanceof ...' – EpicPandaForce

+0

你需要用'if'來檢查它,例如:'if(mineral instanceof Gold){...}' –

回答

1

不能任意對象上進行切換。

您無法打開對象的類。

但是你可以在一個類的對象的名稱進行切換:

switch (mineral.getClass().getName()) { 
    case "some.pkg.Gold": 
     // some stuff 
} 

或者你可以使用mineral.getClass().getSimpleName()和類名切換,而無需包名,等等。

但是,使用instanceof開啓類名稱和測試通常都是「代碼味道」。如果可能的話,最好使用多態性,而不是其他代碼中的不同子類的硬接線特殊情況處理;例如

if (mineral.hasSomeProperty()) { 
    // do stuff 
} 
2

正如評論指出已經,你需要給我們一個ifinstanceof操作是這樣的:

if(mineral instanceof Gold) { 
... 
} 
else if(...) { 
... 
} 
1

你必須使用instaceof檢查的對象類型。

例如:

if(mineral instanceof Gold) 
    System.out.println("mineral is instance of Gold"); 
else if(mineral instanceof Iron) 
    System.out.println("mineral is instance of Iron"); 
else if(mineral instanceof Coal) 
    System.out.println("mineral is instance of Coal"); 

Here you can find clear picture of this instanceof scenario.

1

如果你仍然想使用開關,試試這個:

switch (object.getClass().getSimpleName()){ 
     case : "Gold" 
       //something 
       break; 
     case : "Iron" 
       //something 
       break; 
} 
+2

在對象上沒有方法'getClassName'。 –

+0

@ErwinBolwidt對不起,我已經更新了答案。 –