org.valid4j.ExceptionFactories Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of valid4j Show documentation
Show all versions of valid4j Show documentation
Simple assertion and validation library for Java
package org.valid4j;
import java.lang.reflect.Constructor;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.valid4j.Assertive.neverGetHereError;
import static org.valid4j.Assertive.require;
public class ExceptionFactories {
private ExceptionFactories() {
throw neverGetHereError("Prevent instantiation");
}
public static ExceptionFactory exception(Class exceptionClass) {
require(exceptionClass, notNullValue());
Constructor constructor = findOneStringArgumentPublicConstructor(exceptionClass);
if (constructor != null) {
return new ExceptionOneStringArgumentFactory(constructor);
} else {
constructor = findNoArgumentPublicConstructor(exceptionClass);
if (constructor != null) {
return new ExceptionNoArgumentFactory(constructor);
} else {
throw neverGetHereError("Exception class must have a public constructor accepting one string argument or no arguments. (Note: Inner classes do not satisfy this condition)");
}
}
}
private static Constructor findOneStringArgumentPublicConstructor(Class exceptionClass) {
Constructor> publicConstructors[] = exceptionClass.getConstructors();
for (Constructor> constructor : publicConstructors) {
if (constructor.getParameterTypes().length != 1) {
continue;
}
if (!constructor.getParameterTypes()[0].equals(String.class)) {
continue;
}
return ((Constructor) constructor);
}
return null;
}
private static Constructor findNoArgumentPublicConstructor(Class exceptionClass) {
Constructor> publicConstructors[] = exceptionClass.getConstructors();
for (Constructor> constructor : publicConstructors) {
if (constructor.getParameterTypes().length != 0) {
continue;
}
return ((Constructor) constructor);
}
return null;
}
}