How to call non generic method from a generic one:
class Test {
...
public <T> int someFunction1(T someParam) {
return someFunction2(someParam);
}
public int someFunction2(String someParam) {
return 1;
}
public int someFunction2(Integer someParam) {
return 1;
}
}
Test t = new Test;
t.someFunction1(new String("1"));
t.someFunction1(new Integer(5));
Also is it possible to do this at compile time, rather than at runtime?
The compiler can not determine that someParam
in someFunction1
is either a String
or an Integer
. Something like this will work:
public <T extends String> int someFunction1(T someParam) {
return someFunction2(someParam);
}
public int someFunction2(String someParam) {
return 1;
}
If you wanted it to be String
/Integer
you would need to create some datatype or created overloaded definition of someFunction1
where T
is bound to Integer
Or just some "ugly" casts:
public <T> int someFunction1(T someParam) {
if (someParam instanceof Integer)
return someFunction2((Integer) someParam);
else if (someParam instanceof String)
return someFunction2((String) someParam);
else throw new IllegalArgumentException("Expected String or Integer")
}
You need to check the argument type and according to its type to explicitly cast and call correct method:
public <T> int someFunction1(T someParam) {
if (someParam instanceof Integer)
return someFunction2((Integer)someParam);
else if (someParam instanceof String)
return someFunction2((String)someParam);
else
throw new InvalidArgumentException("Unexepected type: "+someParam.getClass());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With