Vardan Hovhannisyan Vardan Hovhannisyan - 4 months ago 10
Java Question

How to call non generic method from a generic one

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?

Answer

The compiler does not see that someParam in someFunction1 is either a String or 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")
}
Comments