使用泛型匹配参数和返回类型

可以使用泛型将返回类型与参数类型匹配吗?

示例案例:

我有一个抽象类,它将被实现以从不同的 POJO 导入数据,这个类包含一个抽象方法 importData。

从 importData 返回的 Object 必须与传递给方法的 Object 具有相同的类型。

public abstract POJO importData(final POJO dataObject, final String messageId);

由于抽象方法的每个实现的对象类型都不同,并且类型不扩展另一个,如何定义抽象方法以便实现返回类型和传递类型必须匹配?

编辑:

尝试和测试:

public abstract <T> T importData(final T jaxbObject, final String messageId);

结果:

方法的返回类型不必与传递的对象类型匹配。


ABOUTYOU
浏览 203回答 2
2回答

慕的地6264312

您可以使用方法级别的泛型参数:public abstract <T> T importData(final T dataObject, final String messageId);请注意,这种类型T可能因每次调用而异。例如,以下是可能的:POJO myPojo = myClass.importData(otherPojo, "messageId");Integer someInt = myClass.importData(5, "otherMessageId");String aSring = myClass.importData("Hello World", "anotherMessageId");

杨__羊羊

您必须为您的类类型分配一个字母,该字母将在使用您的方法时分配,基于您在调用方法时使用的类型public abstract T importData(final T dataObject, final String messageId);然后,您可以在您的实现中,检查不同行为的对象类型YourAbstractClass c = new YourAbstractClass() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public <T> T importData(T dataObject, String messageId) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(dataObject instanceof String){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //doSomething&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else if (dataObject instanceof POJO){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do POJO things&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java