public static <T> Constructor<T> findConstructor(Class<T> cls, boolean canFixAccess) throws IllegalArgumentException { try { Constructor<T> ctor = cls.getDeclaredConstructor(); if (canFixAccess) { checkAndFixAccess(ctor); } else { // Has to be public... if (!Modifier.isPublic(ctor.getModifiers())) { throw new IllegalArgumentException( "Default constructor for " + cls.getName() + " is not accessible (non-public?): not allowed to try modify access via Reflection: can not instantiate type"); } } return ctor; } catch (NoSuchMethodException e) {; } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE( e, "Failed to find default constructor of class " + cls.getName() + ", problem: " + e.getMessage()); } return null; }
/** * Method that can be called to try to create an instantiate of specified type. Instantiation is * done using default no-argument constructor. * * @param canFixAccess Whether it is possible to try to change access rights of the default * constructor (in case it is not publicly accessible) or not. * @throws IllegalArgumentException If instantiation fails for any reason; except for cases where * constructor throws an unchecked exception (which will be passed as is) */ public static <T> T createInstance(Class<T> cls, boolean canFixAccess) throws IllegalArgumentException { Constructor<T> ctor = findConstructor(cls, canFixAccess); if (ctor == null) { throw new IllegalArgumentException( "Class " + cls.getName() + " has no default (no arg) constructor"); } try { return ctor.newInstance(); } catch (Exception e) { ClassUtil.unwrapAndThrowAsIAE( e, "Failed to instantiate class " + cls.getName() + ", problem: " + e.getMessage()); return null; } }