如何从通用方法中调用非通用方法:

    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));

还有可能在编译时而不是在运行时执行此操作吗?

最佳答案

编译器无法确定someParam中的someFunction1String还是Integer。这样的事情会起作用:

public <T extends String> int someFunction1(T someParam) {
    return someFunction2(someParam);
}

public int someFunction2(String someParam) {
    return 1;
}

如果您希望它是String / Integer,则需要创建某种数据类型或创建someFunction1的重载定义,其中T绑定到Integer
或者只是一些“丑陋”的演员表:
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")
}

10-07 20:30