Overloaded method selection based on the parameter's real type

后端 未结 7 1376
悲哀的现实
悲哀的现实 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 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! :)

提交回复
热议问题