View Javadoc
1   /*
2    * Copyright 2012 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.util;
17  
18  import java.util.concurrent.atomic.AtomicLong;
19  
20  /**
21   * Base implementation of {@link Constant}.
22   */
23  public abstract class AbstractConstant<T extends AbstractConstant<T>> implements Constant<T> {
24  
25      private static final AtomicLong uniqueIdGenerator = new AtomicLong();
26      private final int id;
27      private final String name;
28      private final long uniquifier;
29  
30      /**
31       * Creates a new instance.
32       */
33      protected AbstractConstant(int id, String name) {
34          this.id = id;
35          this.name = name;
36          this.uniquifier = uniqueIdGenerator.getAndIncrement();
37      }
38  
39      @Override
40      public final String name() {
41          return name;
42      }
43  
44      @Override
45      public final int id() {
46          return id;
47      }
48  
49      @Override
50      public final String toString() {
51          return name();
52      }
53  
54      @Override
55      public final int hashCode() {
56          return super.hashCode();
57      }
58  
59      @Override
60      public final boolean equals(Object obj) {
61          return super.equals(obj);
62      }
63  
64      @Override
65      public final int compareTo(T o) {
66          if (this == o) {
67              return 0;
68          }
69  
70          @SuppressWarnings("UnnecessaryLocalVariable")
71          AbstractConstant<T> other = o;
72          int returnCode;
73  
74          returnCode = hashCode() - other.hashCode();
75          if (returnCode != 0) {
76              return returnCode;
77          }
78  
79          if (uniquifier < other.uniquifier) {
80              return -1;
81          }
82          if (uniquifier > other.uniquifier) {
83              return 1;
84          }
85  
86          throw new Error("failed to compare two different constants");
87      }
88  
89  }