[英]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.