org.unitils.objectvalidation.rules.ClassMustBeSerializableRule Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of unitils-objectvalidation Show documentation
Show all versions of unitils-objectvalidation Show documentation
Unitils module to validate objects.
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()));
}
}