Java Reflection calling constructor with primitive types

后端 未结 6 1160
日久生厌
日久生厌 2020-11-29 10:07

I have a method in my test framework that creates an instance of a class, depending on the parameters passed in:

public void test(Object... constructorArgs)          


        
6条回答
  •  感情败类
    2020-11-29 10:26

    Since the primitive types are autoboxed, the getConstructor(java.lang.Class... parameterTypes) call will fail. You will need to manually loop through the available constructors. If all types match then you're fine. If some types do not match, but the required type is a primitive AND the available type is the corresponding wrapper class, then you can use that constructor. See bellow:

    static  Constructor getAppropriateConstructor(Class c, Object[] initArgs){
        if(initArgs == null)
            initArgs = new Object[0];
        for(Constructor con : c.getDeclaredConstructors()){
            Class[] types = con.getParameterTypes();
            if(types.length!=initArgs.length)
                continue;
            boolean match = true;
            for(int i = 0; i < types.length; i++){
                Class need = types[i], got = initArgs[i].getClass();
                if(!need.isAssignableFrom(got)){
                    if(need.isPrimitive()){
                        match = (int.class.equals(need) && Integer.class.equals(got))
                        || (long.class.equals(need) && Long.class.equals(got))
                        || (char.class.equals(need) && Character.class.equals(got))
                        || (short.class.equals(need) && Short.class.equals(got))
                        || (boolean.class.equals(need) && Boolean.class.equals(got))
                        || (byte.class.equals(need) && Byte.class.equals(got));
                    }else{
                        match = false;
                    }
                }
                if(!match)
                    break;
            }
            if(match)
                return con;
        }
        throw new IllegalArgumentException("Cannot find an appropriate constructor for class " + c + " and arguments " + Arrays.toString(initArgs));
    }
    

提交回复
热议问题