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

com.spikeify.NoArgClassConstructor Maven / Gradle / Ivy

There is a newer version: 0.2.35
Show newest version
package com.spikeify;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * A ClassConstructor implementation that uses no-argument constructor to instantiate objects
 */
@SuppressWarnings("WeakerAccess")
public class NoArgClassConstructor implements ClassConstructor {

	public  T construct(Class type) {

		Constructor ctor = NoArgClassConstructor.getNoArgConstructor(type);
		return NoArgClassConstructor.newInstance(ctor);
	}

	public static  T newInstance(Constructor ctor, Object... params) {

		try {
			return ctor.newInstance(params);
		}
		catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
			throw new RuntimeException(e);
		}
	}

	 /**
	 * Throw an SpikeifyError if the class does not have a no-arg constructor.
	 *
	 * @param  type
	 * @param clazz class type
	 * @return found constructor
	 */
	public static  Constructor getNoArgConstructor(Class clazz) {

		try {
			Constructor ctor = clazz.getDeclaredConstructor();
			ctor.setAccessible(true);
			return ctor;
		}
		catch (NoSuchMethodException e) {
			if (clazz.isMemberClass() || clazz.isAnonymousClass() || clazz.isLocalClass()) { throw new SpikeifyError(clazz.getName() + " must be static and must have a no-arg constructor", e); }
			else { throw new SpikeifyError(clazz.getName() + " must have a no-arg constructor", e); }
		}
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy