Overloaded method selection based on the parameter's real type

后端 未结 7 1367
悲哀的现实
悲哀的现实 2020-11-22 01:39

I\'m experimenting with this code:

interface Callee {
    public void foo(Object o);
    public void foo(String s);
    public void foo(Integer i);
}

class          


        
7条回答
  •  有刺的猬
    2020-11-22 02:28

    In Java the method to call (as in which method signature to use) is determined at compile time, so it goes with the compile time type.

    The typical pattern for working around this is to check the object type in the method with the Object signature and delegate to the method with a cast.

        public void foo(Object o) {
            if (o instanceof String) foo((String) o);
            if (o instanceof Integer) foo((Integer) o);
            logger.debug("foo(Object o)");
        }
    

    If you have many types and this is unmanageable, then method overloading is probably not the right approach, rather the public method should just take Object and implement some kind of strategy pattern to delegate the appropriate handling per object type.

提交回复
热议问题