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

org.unitils.objectvalidation.rules.PrivateConstructorRule Maven / Gradle / Ivy

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy