Java tutorial
/* * Copyright (c) 2016 Prasenjit Purohit * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.prasenjit.auth.validation; import org.springframework.util.ReflectionUtils; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.lang.reflect.Field; /** * Created by PRASENJIT-NET on 5/2/2016. * * @author PRASEN * @version $Id: $Id */ public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> { private String firstFieldName; private String secondFieldName; /** * {@inheritDoc} */ @Override public void initialize(final FieldMatch constraintAnnotation) { firstFieldName = constraintAnnotation.first(); secondFieldName = constraintAnnotation.second(); } /** {@inheritDoc} */ @Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { try { Field field = ReflectionUtils.findField(value.getClass(), firstFieldName); ReflectionUtils.makeAccessible(field); final Object firstObj = ReflectionUtils.getField(field, value); field = ReflectionUtils.findField(value.getClass(), secondFieldName); ReflectionUtils.makeAccessible(field); final Object secondObj = ReflectionUtils.getField(field, value); return firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj); } catch (final Exception ignore) { // ignore } return true; } }