My first post here - I hope to give you all info required. I tried to check online anmd in forum but I cannot find the same case - maybe is not possible -.-'
This is my situation:
I have two classes with same properties (I cannot change it, add an interface or abstract class)
public class InputA {
private String status;
private String name;
....
}
public class InputB {
private String status;
private String name;
....
}
private <T> VerifyRequest createVerifyRequest(T input) {
if (input instanceof InputA)
input = (InputA) input;
if (input instanceof InputB)
input = (InputB) input;
VerifyRequest request = new VerifyRequest;
verifyRequest.setStatus (input.getStatus());
....
....
....
return request;
}
My idea is to cast because I know only two different type are possible.
What am I missing?
Thanks in advance for your support ^^
I tried to pass Object too
private VerifyRequest createVerifyRequest(Object input) {
if (input instanceof InputA)
input = (InputA) input
if (input instanceof InputB)
input = (InputB) input;
VerifyRequest request = new VerifyRequest;
verifyRequest.setStatus (input.getStatus()); //this give me error (Cannot resolve getStatus in Object)
CodePudding user response:
input
is of type T
so you can't cast it to InputA
or InputB
. You could do something like below but it is not that elegant:
private <T> VerifyRequest createVerifyRequest(T input) {
VerifyRequest request = new VerifyRequest();
if (input instanceof InputA){
InputA a = (InputA) input;
request.setStatus (a.getStatus());
}
else if (input instanceof InputB){
InputB b = (InputB) input;
request.setStatus (b.getStatus());
}
return request;
}