简体   繁体   English

如何实例化(在方法内部)实现同一接口的不同类?

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

相关问题 动态实例化实现接口并调用接口方法的类 - Dynamically instantiate classes which implement an interface and invoke interface method 实现相同接口的多个类的方法相同 - Same method for multiple classes that implement the same interface 如何在仅使用批注实现相同接口的不同类中使用@autowired - How to use @autowired in different classes that implement the same interface with only annotations 如何从不同的接口实现相同的接口方法 - Retrofit 和 Twitter - How to implement same Interface method from different Interfaces - Retrofit and Twitter 在Java中,如何区分实现相同接口的类? - In Java, how to distinguish classes that implement the same interface? 如何在类列表中实现不常用的方法/接口? - How to implement infrequent method/interface in list of classes? 如何注入实现同一接口的两个不同类的两个实例? - How to inject two instances of two different classes which implement the same interface? 如何给两个不同的类相同的接口? - How to give two different classes the same interface? 如何使用相同的变量名实例化不同类的对象 - How to use same variable name to instantiate the object of different classes 如何为不同类别的不同数据类型实现接口 - How to implement an interface for different classes of different data types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM