![](/img/trans.png)
[英]Dynamically instantiate classes which implement an interface and invoke interface method
[英]How to instantiate (inside a method) different classes that implement the same interface?
只是想知道您是否能夠幫助我解決我的問題。 這可能是由於我不知道要搜索的關鍵字是否正確。
這不是作業,只是匿名...
我有一個接口和一堆實現類:
interface Fruit
Banana implements Fruit
Apple implements Fruit
....
我有一個Fruit實用程序類。 在這種方法中,需要使用任何種類的Fruit並將其切成薄片。
public static Fruit[] slice(Fruit f, int pieces)
如何聲明Fruit數組與傳遞給該方法的Fruit類型相同?
即我如何自動化:
Fruit[] a = new Apple[pieces];
如果我給它一個蘋果?
。
編輯:澄清
我將有這樣的代碼:
Fruit a = new Apple();
Fruit b = new Banana();
Fruit[] slices1 = FruitUtil.slice(a, 3); //slices1 should be an Apple
Fruit[] slices2 = FruitUtil.slice(b, 3); //slices2 should be a Banana
Fruit newApple = FruitUtil.copy(a); //newApple should be an Apple
如何編寫slice(Fruit f,int slice)或copy(Fruit f)方法,以便創建與參數中傳遞的水果類型相同的水果(而不必覆蓋每種類型的方法,也不必執行instanceof檢查) )
首先,我建議放棄引用數組。 請改用List
。 然后,它相對簡單:
public static <T extends Fruit> List<T> slice(T fruit, int pieces)
或者,您可以使用反射:Array.newInstance(f.getClass(),piece)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.