[英]How to instantiate (inside a method) different classes that implement the same interface?
Just wondering if you're able to help me with my problem. 只是想知道您是否能够帮助我解决我的问题。 This has probably come about by my not knowing the right keywords to search for.
这可能是由于我不知道要搜索的关键字是否正确。
This is not homework, just anonymised... 这不是作业,只是匿名...
I have an interface and a bunch of implementing classes: 我有一个接口和一堆实现类:
interface Fruit
Banana implements Fruit
Apple implements Fruit
....
I have a Fruit utilities class. 我有一个Fruit实用程序类。 In this is a method that takes any sort Fruit and slices it.
在这种方法中,需要使用任何种类的Fruit并将其切成薄片。
public static Fruit[] slice(Fruit f, int pieces)
How can I declare the Fruit array to be of the same type as the Fruit I pass to the method? 如何声明Fruit数组与传递给该方法的Fruit类型相同?
ie How can I automate: 即我如何自动化:
Fruit[] a = new Apple[pieces];
if I give it an Apple? 如果我给它一个苹果?
. 。
edit:clarification 编辑:澄清
I'll have code like this: 我将有这样的代码:
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
How do I write slice(Fruit f, int slice) or copy(Fruit f) method such that I create the same type of Fruit as what I passed in the arguments (without having to override the method for each type, or doing instanceof checks) 如何编写slice(Fruit f,int slice)或copy(Fruit f)方法,以便创建与参数中传递的水果类型相同的水果(而不必覆盖每种类型的方法,也不必执行instanceof检查) )
Firstly I suggest giving up arrays of references. 首先,我建议放弃引用数组。 Use
List
instead. 请改用
List
。 Then it is relatively simple: 然后,它相对简单:
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.