Search in sources :

Example 1 with PrimitiveType

use of org.hibernate.type.PrimitiveType in project hibernate-orm by hibernate.

the class ReflectHelper method getConstructor.

/**
	 * Retrieve a constructor for the given class, with arguments matching the specified Hibernate mapping
	 * {@link Type types}.
	 *
	 * @param clazz The class needing instantiation
	 * @param types The types representing the required ctor param signature
	 * @return The matching constructor.
	 * @throws PropertyNotFoundException Indicates we could not locate an appropriate constructor (todo : again with PropertyNotFoundException???)
	 */
public static Constructor getConstructor(Class clazz, Type[] types) throws PropertyNotFoundException {
    final Constructor[] candidates = clazz.getConstructors();
    Constructor constructor = null;
    int numberOfMatchingConstructors = 0;
    for (final Constructor candidate : candidates) {
        final Class[] params = candidate.getParameterTypes();
        if (params.length == types.length) {
            boolean found = true;
            for (int j = 0; j < params.length; j++) {
                final boolean ok = types[j] == null || params[j].isAssignableFrom(types[j].getReturnedClass()) || (types[j] instanceof PrimitiveType && params[j] == ((PrimitiveType) types[j]).getPrimitiveClass());
                if (!ok) {
                    found = false;
                    break;
                }
            }
            if (found) {
                numberOfMatchingConstructors++;
                candidate.setAccessible(true);
                constructor = candidate;
            }
        }
    }
    if (numberOfMatchingConstructors == 1) {
        return constructor;
    }
    throw new PropertyNotFoundException("no appropriate constructor in class: " + clazz.getName());
}
Also used : PropertyNotFoundException(org.hibernate.PropertyNotFoundException) Constructor(java.lang.reflect.Constructor) PrimitiveType(org.hibernate.type.PrimitiveType)

Aggregations

Constructor (java.lang.reflect.Constructor)1 PropertyNotFoundException (org.hibernate.PropertyNotFoundException)1 PrimitiveType (org.hibernate.type.PrimitiveType)1