2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.so.openpojo.rules;
23 import static org.hamcrest.CoreMatchers.anyOf;
24 import static org.hamcrest.CoreMatchers.anything;
26 import java.lang.reflect.Method;
27 import java.lang.reflect.Parameter;
29 import org.hamcrest.Matcher;
31 import com.openpojo.reflection.PojoClass;
32 import com.openpojo.validation.affirm.Affirm;
33 import com.openpojo.validation.rule.Rule;
36 * This rule ensures that classes have overriden the default equals and hashCode methods from Object
38 public class HasEqualsAndHashCodeRule implements Rule {
40 private final Matcher m;
41 public HasEqualsAndHashCodeRule() {
45 public HasEqualsAndHashCodeRule(Matcher m) {
49 public void evaluate(PojoClass pojoClass) {
50 Class<?> clazz = pojoClass.getClazz();
51 if (anyOf(m).matches(clazz)) {
52 boolean hasEquals = false;
53 boolean hasHashCode = false;
54 final String name = clazz.getSimpleName();
55 final Method[] methods;
56 if (clazz.getSuperclass().equals(Object.class)) {
57 methods = clazz.getDeclaredMethods();
59 methods = clazz.getMethods();
61 for (Method method : methods) {
62 Parameter[] parameters = method.getParameters();
63 if ("equals".equals(method.getName()) && boolean.class.equals(method.getReturnType()) && parameters.length == 1 && Object.class.equals(parameters[0].getType())) {
65 } else if ("hashCode".equals(method.getName()) && int.class.equals(method.getReturnType())) {
71 Affirm.fail(String.format(
72 "[%s] does not override equals", name));
75 Affirm.fail(String.format(
76 "[%s] does not override hashCode", name));