Define OpaqueData/OpaqueObject hashCode/equals
[mdsal.git] / binding / yang-binding / src / main / java / org / opendaylight / yangtools / yang / binding / AbstractOpaqueObject.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.binding;
9
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.MoreObjects;
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import org.eclipse.jdt.annotation.NonNull;
14
15 /**
16  * Utility base class for {@link OpaqueObject} implementations. This class provides baseline implementation of
17  * {@link #hashCode()} and {@link #equals(Object)} as specified by {@link OpaqueObject}.
18  *
19  * @param <T> Implemented OpaqueObject type
20  */
21 @Beta
22 public abstract class AbstractOpaqueObject<T extends OpaqueObject<T>> implements OpaqueObject<T> {
23     @Override
24     public final int hashCode() {
25         return 31 * getImplementedInterface().hashCode() + valueHashCode();
26     }
27
28     @Override
29     public final boolean equals(final Object obj) {
30         if (this == obj) {
31             return true;
32         }
33         if (!(obj instanceof OpaqueObject)) {
34             return false;
35         }
36         final OpaqueObject<?> other = (OpaqueObject<?>) obj;
37         return getImplementedInterface().equals(other.getImplementedInterface()) && valueEquals(other.getValue());
38     }
39
40     @Override
41     public final String toString() {
42         return addToStringAttributes(MoreObjects.toStringHelper(this)
43             .add("implementedInterface", getImplementedInterface())).toString();
44     }
45
46     protected ToStringHelper addToStringAttributes(final ToStringHelper helper) {
47         return helper.add("value", getValue());
48     }
49
50     protected boolean valueEquals(final @NonNull OpaqueData<?> otherValue) {
51         return getValue().equals(otherValue);
52     }
53
54     protected int valueHashCode() {
55         return getValue().hashCode();
56     }
57 }