All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.valid4j.ExceptionFactories Maven / Gradle / Ivy

There is a newer version: 0.5.0
Show newest version
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;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy