Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call non generic method from a generic one

Tags:

java

generics

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?

like image 940
Vardan Hovhannisyan Avatar asked Jan 05 '23 18:01

Vardan Hovhannisyan


2 Answers

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")
}
like image 121
raphaëλ Avatar answered Jan 08 '23 07:01

raphaëλ


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());
}
like image 26
Zbynek Vyskovsky - kvr000 Avatar answered Jan 08 '23 08:01

Zbynek Vyskovsky - kvr000