org.unitils.objectvalidation.rules.NoPublicFieldsRule 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.
/**
* Copyright (C) 2010 Osman Shoukry
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package org.unitils.objectvalidation.rules;
import static org.junit.Assert.fail;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import org.unitils.objectvalidation.Rule;
import org.unitils.util.ReflectionUtils;
/**
* This rule ensures that no fields declared with public visibility.
* Only those that are static final. public static fields should always be final to avoid funky shit
* in the application.
*
* @author Thomas De Rycke
*
* @since 1.1.6
*
* @see Object Validation module
*/
public final class NoPublicFieldsRule implements Rule {
/**
* @see org.unitils.objectvalidation.Rule#validate(java.lang.Class)
*/
@Override
public void validate(Class> classToValidate) {
for (Field fieldEntry : ReflectionUtils.getAllFields(classToValidate)) {
boolean isFinal = Modifier.isFinal(fieldEntry.getModifiers());
boolean isStatic = Modifier.isStatic(fieldEntry.getModifiers());
boolean isPublic = Modifier.isPublic(fieldEntry.getModifiers());
if (!(isFinal && isStatic) && isPublic) {
fail(String.format("Public fields=[%s] not allowed", fieldEntry));
}
}
}
}