Overloaded method selection based on the parameter's real type

后端 未结 7 1382
悲哀的现实
悲哀的现实 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:12

    I had a similar issue with calling the right constructor of a class called "Parameter" that could take several basic Java types such as String, Integer, Boolean, Long, etc. Given an array of Objects, I want to convert them into an array of my Parameter objects by calling the most-specific constructor for each Object in the input array. I also wanted to define the constructor Parameter(Object o) that would throw an IllegalArgumentException. I of course found this method being invoked for every Object in my array.

    The solution I used was to look up the constructor via reflection...

    public Parameter[] convertObjectsToParameters(Object[] objArray) {
        Parameter[] paramArray = new Parameter[objArray.length];
        int i = 0;
        for (Object obj : objArray) {
            try {
                Constructor<Parameter> cons = Parameter.class.getConstructor(obj.getClass());
                paramArray[i++] = cons.newInstance(obj);
            } catch (Exception e) {
                throw new IllegalArgumentException("This method can't handle objects of type: " + obj.getClass(), e);
            }
        }
        return paramArray;
    }
    

    No ugly instanceof, switch statements, or visitor pattern required! :)

    0 讨论(0)
  • 2020-11-22 02:18

    If there is an exact match between the number and types of arguments specified in the method call and the method signature of an overloaded method then that is the method that will be invoked. You are using Object references, so java decides at compile time that for Object param, there is a method which accepts directly Object. So it called that method 3 times.

    0 讨论(0)
  • 2020-11-22 02:22

    I expect the method selection to take in consideration the real (not the declared) parameter type. Am I missing something?

    Yes. Your expectation is wrong. In Java, dynamic method dispatch happens only for the object the method is called on, not for the parameter types of overloaded methods.

    Citing the Java Language Specification:

    When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:30

    Java looks at the reference type when trying to determine which method to call. If you want to force your code you choose the 'right' method, you can declare your fields as instances of the specific type:

    Integeri = new Integer(12);
    String s = "foobar";
    Object o = new Object();
    

    You could also cast your params as the type of the param:

    callee.foo(i);
    callee.foo((String)s);
    callee.foo(((Integer)o);
    
    0 讨论(0)
  • 2020-11-22 02:37

    Ability to dispatch a call to a method based on types of arguments is called multiple dispatch. In Java this is done with Visitor pattern.

    However, since you're dealing with Integers and Strings, you cannot easily incorporate this pattern (you just cannot modify these classes). Thus, a giant switch on object run-time will be your weapon of choice.

    0 讨论(0)
提交回复
热议问题