简体   繁体   English

实现接口以调用相同方法的类数组

[英]Array of classes implementing an interface to call same method

I have 4 classes, all implementing an interface IntSorter . 我有4个类,都实现一个接口IntSorter All classes have a sort method, so for each class I want to call sort on an array. 所有类都有一个sort方法,因此对于每个类,我想在数组上调用sort

I thought something like this would work: 我认为这样会起作用:

IntSorter[] classes = new IntSorter[] {
Class1.class, Class2.class, Class3.class, Class4.class
};
for (Class c : classes)
    c.sort(array.clone());

But classes cannot hold the .class names, I get the error Type mismatch: cannot convert from Class<Class1> to IntSorter 但是classes无法保存.class名称,我收到错误Type mismatch: cannot convert from Class<Class1> to IntSorter

So I tried 所以我尝试了

Class[] classes = new Class[] {
Class1.class, Class2.class, Class3.class, Class4.class
};
for (Class c : classes)
    c.sort(array.clone());

But now c.sort() cannot be called. 但是现在无法调用c.sort()。 I tried parsing the class to an IntSorter first, with (IntSorter) c but then I get the error Cannot cast from Class to IntSorter 我尝试首先使用(IntSorter) c将类解析为IntSorter,但是随后出现错误Cannot cast from Class to IntSorter

How do I fix this? 我该如何解决?

Use the first approach, but you want for (IntSorter c : classes) - and you need to put instances in your array (not the classes). 使用第一种方法,但是要for (IntSorter c : classes) -并且需要将实例放入数组(而不是类)中。 Something like, 就像是,

IntSorter[] classes = new IntSorter[] {
    new Class1(), new Class2(), new Class3(), new Class4()
};
for (IntSorter c : classes) {
    c.sort(array.clone());
}

You are attempting to create array of classes instead of array of instances of classes implementing IntSorter . 您正在尝试创建类数组而不是实现IntSorter的类实例数组。

Check this question to understand difference between Classes, Objects and Instances: The difference between Classes, Objects, and Instances 检查此问题以了解类,对象和实例之间的区别 :类,对象和实例之间的区别

Your code should look something like this, as far as I can tell with limited information available: 就我所提供的有限信息而言,您的代码应该看起来像这样:

IntSorter[] classes = new IntSorter[] {
new Class1(), new Class2(), new Class3(), new Class4()
};
for (IntSorter c : classes)
    c.sort(array.clone());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM