问题
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