简体   繁体   English

Java接口 - 参数多态

[英]Java interfaces - parametric polymorphism

In Java what's the "correct" way to implement an interface where the parameters for a method need parametric polymorphism? 在Java中,实现接口的“正确”方法是什么,方法的参数需要参数多态?

For example, my interface contains: 例如,我的界面包含:

public int addItem(Object dto);

The interface is implemented by various classes but in each the dto parameter is one of various strongly typed objects such as planeDTO, trainDTO or automobileDTO. 该接口由各种类实现,但在每个类中,dto参数是各种强类型对象之一,例如planeDTO,trainDTO或automobileDTO。

For example, in my planeDAO class: 例如,在我的planeDAO类中:

public int addItem(planeDTO dto) { ... }

Do I simply implement with the dto parameter as Object and then cast to the appropriate type? 我只是使用dto参数作为Object实现,然后转换为适当的类型?

If the DTOs all inhrerit from a common superclass or implement a common interface you can do: 如果DTO完全来自公共超类或实现公共接口,您可以:

// DTO is the common superclass/subclass
public interface Addable<E extends DTO> {

    public int addItem(E dto);

}

And your specific implementations can do: 您的具体实施可以做到:

public class PlaneImpl implements Addable<planeDTO> {
    public int addItem(planeDTO dto) { ... }
}

Or, you can simply define your interface to take in the interface/superclass: 或者,您可以简单地定义接口以接受接口/超类:

// DTO is the common superclass/subclass
public interface Addable {

    public int addItem(DTO dto);

}

Edit: 编辑:

What you may need to do is the following: 您可能需要做的是以下内容:

Create interface - 创建界面 -

interface AddDto<E> {
    public int addItem(E dto);
}

And implement it in your DAOs. 并在您的DAO中实现它。

class planeDAO implements AddDto<planeDTO> {
    public int addItem(planeDTO dto) { ... }
}

Why not use an interface which provides the functionality you need and not reference the concrete types? 为什么不使用提供所需功能的接口而不引用具体类型?

public int addItem(ITransportationMode mode);

Where planeDTO , trainDTO and automobileDTO all implement ITransportationMode 其中planeDTOtrainDTOautomobileDTO都实现了ITransportationMode

Are you trying to reach for something like double dispatch ? 你想要达到像双重派遣这样的东西吗? What is the behaviour which varies depending on the type of the argument? 根据参数类型的不同,行为是什么?

You could also use generic methods: 您还可以使用泛型方法:

public interface Addable{
   public <T extends DTO> int addItem(T dto){}
}

You can read more about generic methods at : http://download.oracle.com/javase/tutorial/extra/generics/methods.html 您可以在以下网址阅读有关泛型方法的更多信息: http//download.oracle.com/javase/tutorial/extra/generics/methods.html

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

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