[英]Interface definition and generics. Should this be defined differently?
I have a class Employee
and a class Building
. 我有一个班级的
Employee
和一个班级的Building
。
These classes are not related to each other from class hierarchy perspective. 从类层次结构的角度来看,这些类彼此不相关。
I need to process a bunch of Employee
and Building
objects and their results will end up in different lists. 我需要处理一堆
Employee
和Building
对象,它们的结果将出现在不同的列表中。
So I have and interface eg 所以我有接口
public interface Processor{
public void process(String s, List<?> result);
}
The idea is that the string s
carries information related to either an Employee
or a Building
and the implementation after some processing adds to the result list either an Employee
object or a Building
object. 想法是,字符串
s
携带与Employee
或Building
有关s
信息,并且经过一些处理后,实现将Employee
对象或Building
对象添加到结果列表中。
There are 2 implementations of Processor
one is EmployeeProcessor
and a BuildingProcessor
. 有2个实施方案中
Processor
之一是EmployeeProcessor
和BuildingProcessor
。
Somewhere in the code I get a reference to either of these and I pass either a List<Employee>
or a List<Building>
to the process
method. 在代码中的某个地方,我获得了对这两个方法的引用,并将
List<Employee>
或List<Building>
传递给了process
方法。
Problem is that the code does not compile. 问题是代码无法编译。
When I do eg inside the EmployeeProcessor
: result.add(new Employee(a,b,c,d));
当我在
EmployeeProcessor
内部执行操作时: result.add(new Employee(a,b,c,d));
I get: 我得到:
The method add(capture#2-of ?) in the type List is not applicable for the arguments
类型List中的方法add(capture#2-of?)不适用于自变量
I guess I can understand the problem, but I don't want to change the interface to: 我想我可以理解问题,但是我不想将界面更改为:
public interface Processor{
public process(String s, List result);
}
Ie not specify type of list. 即不指定列表类型。
Is there a way around this problem? 有办法解决这个问题吗? Is the interface definition wrong?
接口定义是否错误?
Note: this interface is part of implementation of Command
pattern 注意:此接口是
Command
模式实现的一部分
This is what I was thinking. 这就是我的想法。
interface Processor<T>{
public void process(String s, List<T> result);
}
class BuildingProcessor implements Processor<Building>{
@Override
public void process(String s, List<Building> result) {
result.add(new Building());
}
}
class EmployeeProcessor implements Processor<Employee>{
@Override
public void process(String s, List<Employee> result) {
result.add(new Employee());
}
}
FYI, you can further limit the type. 仅供参考,您可以进一步限制类型。 For example, if both
Building
and Employee
classes implement, lets say, Processable
, then you can do interface Processor<T extends Processable>
例如,如果
Building
和Employee
类都实现,比如说Processable
,那么您可以执行interface Processor<T extends Processable>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.