org.unitils.objectvalidation.rules.PrivateConstructorRule Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of unitils-objectvalidation Show documentation
Show all versions of unitils-objectvalidation Show documentation
Unitils module to validate objects.
package org.unitils.objectvalidation.rules;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import org.unitils.objectvalidation.Rule;
/**
* Rule to check that no public constructors are available on the tested class.
*
* @author Matthieu Mestrez
* @since Oct 23, 2013
*/
public class PrivateConstructorRule implements Rule {
@Override
public void validate(Class> classToValidate) {
try {
assertTrue("The constructors should be hidden for the class " + classToValidate.getName() + " create a private constructor.", classToValidate.getConstructors().length == 0);
Constructor>[] constructors = classToValidate.getDeclaredConstructors();
assertNotNull("There was no constructor", constructors);
for (Constructor> constructor : constructors) {
assertTrue(Modifier.isPrivate(constructor.getModifiers()));
if (! constructor.isSynthetic() && constructor.getParameterTypes().length == 0) {
constructor.setAccessible(true);
assertNotNull(constructor.newInstance());
}
}
} catch (IllegalArgumentException e) {
throw new AssertionError("Could not instantiate private constructor : " + e.getMessage());
} catch (InstantiationException e) {
throw new AssertionError("Could not instantiate private constructor : " + e.getMessage());
} catch (IllegalAccessException e) {
throw new AssertionError("Could not instantiate private constructor : " + e.getMessage());
} catch (InvocationTargetException e) {
throw new AssertionError("Could not instantiate private constructor : " + e.getMessage());
}
}
}