Java: newInstance of class that has no default constructor

前端 未结 6 799
广开言路
广开言路 2020-11-29 02:32

I\'m trying to build an automatic testing framework (based on jUnit, but that\'s no important) for my students\' homework. They will have to create constructors for some cla

6条回答
  •  心在旅途
    2020-11-29 03:20

    Here is a generic solution that does not require javassist or another bytecode "manipulator". Although, it assumes that constructors are not doing anything else than simply assigning arguments to corresponding fields, so it simply picks the first constructor and creates an instance with default values (i.e. 0 for int, null for Object etc.).

    private  T instantiate(Class cls, Map args) throws Exception
    {
        // Create instance of the given class
        final Constructor constr = (Constructor) cls.getConstructors()[0];
        final List params = new ArrayList();
        for (Class pType : constr.getParameterTypes())
        {
            params.add((pType.isPrimitive()) ? ClassUtils.primitiveToWrapper(pType).newInstance() : null);
        }
        final T instance = constr.newInstance(params.toArray());
    
        // Set separate fields
        for (Map.Entry arg : args.entrySet()) {
            Field f = cls.getDeclaredField(arg.getKey());
            f.setAccessible(true);
            f.set(instance, arg.getValue());
        }
    
        return instance;
    }
    
    
    

    P.S. Works with Java 1.5+. The solution also assumes there's no SecurityManager manager that could prevent invocation of f.setAccessible(true).

    提交回复
    热议问题