Choose return class type based on parameter with Java 7

倖福魔咒の 提交于 2020-01-05 00:46:11

问题


I am looking for whether is possible or not to make this in Java 7:

Now, I have this functions like this in several services, which third parameter will be diffent in each one:

final RequestDTO1 requestDTO = (RequestDTO1) getDTO(param, RequestDTO1.class);

final RequestDTO2 requestDTO = (RequestDTO2) getDTO(param, RequestDTO2.class);

final RequestDTO3 requestDTO = (RequestDTO3) getDTO(param, RequestDTO3.class);

This is the getDTO signature:

protected Object getMessage(Object param, Class clazz);

There is some way of indicating the getDTO function that I want to return an object of the class indicated by the third parameter without using the casting?

final RequestDTO1 requestDTO = getDTO(param, RequestDTO1.class);

final RequestDTO2 requestDTO = getDTO(param, RequestDTO2.class);

final RequestDTO3 requestDTO = getDTO(param, RequestDTO3.class);

回答1:


You can specify the method is generified (note this is independent from the class generification - it is done at a method level), and return the generic type like this:

protected <T> T getMessage(Object param, Class<T> clazz);

See the Generic methods section in the Java Tutorial for more information.




回答2:


try this

protected <T> T getMessage(Object param, Class<T> clazz);



回答3:


Try:

protected <T> T getMessage(Object param, Class<T> clazz);


来源:https://stackoverflow.com/questions/17545170/choose-return-class-type-based-on-parameter-with-java-7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!