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

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

There is a newer version: 1.1.9
Show newest version
package org.unitils.objectvalidation.rules;

import static java.lang.reflect.Modifier.isFinal;
import static java.lang.reflect.Modifier.isPrivate;
import static java.lang.reflect.Modifier.isStatic;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.unitils.util.ReflectionUtils.getFieldWithName;

import java.io.Serializable;
import java.lang.reflect.Field;

import org.hamcrest.CoreMatchers;
import org.unitils.objectvalidation.Rule;


/**
 * Rule to check that the class passed in parameter must implement {@link java.io.Serializable}.
 * 
 * @author Matthieu Mestrez
 * @since Oct 23, 2013
 */
public class ClassMustBeSerializableRule implements Rule {
    
    @Override
    public void validate(Class classToValidate) {
        assertThat("Class is not Serializable.", classToValidate, CoreMatchers.instanceOf(Serializable.class));
        assertSerialsVersionUIDExists(classToValidate);
    }

    private void assertSerialsVersionUIDExists(Class classToValidate) {
        Field field = getFieldWithName(classToValidate, "serialVersionUID", true);
        assertNotNull("Class does not contains serialVersionUID field.", field);
        assertTrue("serialVersionUID is not final.", isFinal(field.getModifiers()));
        assertTrue("serialVersionUID is not private", isPrivate(field.getModifiers()));
        assertTrue("serialVersionUID is not static", isStatic(field.getModifiers()));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy