Reputation: 1141
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?
Upvotes: 4
Views: 867
Reputation: 6523
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")
}
Upvotes: 5
Reputation: 7285
This answer would only work if the the parameter is always a string or a Integer
public <T> int someFunction1(T someParam) {
try {
return someFunction2((String) someParam);
} catch (ClassCastException e) {
try {
return someFunction2((int) someParam);
} catch (ClassCastException ex) {
return 0;
}
}
}
Upvotes: 0
Reputation: 140328
The generics don't add anything. You can (and should) remove the type variable from the method without changing behaviour:
public int someFunction1(Object someParam) {
and then apply one of the if/else
instanceof
chains proposed in the other answers.
Upvotes: 0
Reputation: 18825
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());
}
Upvotes: 4