如何为Java对象找到最好的构造函数?

时间:2017-02-10 11:52:17

标签: java reflection

给定一个Java类,它具有多个构造函数和一个对象数组,可用作任何构造函数的参数。找到构造函数的最佳方法是哪个参数列表与给定值更接近匹配?

以下是我到目前为止所尝试的内容,它基本上是从值的类开始,只是尝试为0,1或2个构造函数参数实例化构造函数。但我正在为N个参数寻找通用的东西,就像Java从一组重载的方法中选择最好的方法一样。

我的动机是,我有一个通用的Collection<T>,其方法add(Object... params)必须根据可用数据创建T的“最佳”实例。

import java.lang.reflect.Constructor;

public class ObjectFactory {

    /**
     * Get the constructor for a class that matches the given parameter classes.
     * @param objectClass Class&lt;? extends Object&gt;
     * @param parameterClasses Class&lt;?&gt;[]
     * @return Constructor&lt;? extends Object&gt; or <b>null</b> if there is no constructor with given parameters at the class.
     */
    public static Constructor<? extends Object> getConstructor(Class<? extends Object> objectClass, Class<?>[] parameterClasses) {
        Constructor<? extends Object> objectContructor = null;

        // Try a constructor which signature matches exactly the given classes
        objectContructor = tryConstructor(objectClass, parameterClasses);

        if (null==objectContructor && parameterClasses.length==2) {
            // Try a constructor with one parameter which class matches any of two given classes
            objectContructor = tryConstructor(objectClass, parameterClasses[0]);
            if (null==objectContructor)
                objectContructor = tryConstructor(objectClass, parameterClasses[1]);

            // Use default constructor
            if (null==objectContructor)
                objectContructor = tryConstructor(objectClass);
        }
        return objectContructor;
    }

    /**
     * Try to get a constructor using reflection, if an exception is thrown, catch it and return null
     * @return Constructor&lt;? extends Object&gt; or <b>null</b>
     */
    protected static Constructor<? extends Object> tryConstructor(Class<? extends Object> objectClass, Class<?>... parameterClasses) {
        Constructor<? extends Object> objectConstructor = null;
        try {
            if (parameterClasses==null || parameterClasses.length==0)
                objectConstructor = objectClass.getConstructor();
            else
                objectConstructor = objectClass.getConstructor(parameterClasses);
        }
        catch (SecurityException secxcpt) { }
        catch (NoSuchMethodException notfound) { }
        return objectConstructor;
    }   
}

0 个答案:

没有答案