View Javadoc
1   /*
2    * Licensed under the GPL License. You may not use this file except in compliance with the License.
3    * You may obtain a copy of the License at
4    *
5    *   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6    *
7    * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8    * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9    * PURPOSE.
10   */
11  package psiprobe.tools;
12  
13  /**
14   * Wraps an object that may have overridden the {@link Object#equals(Object) equals()} and
15   * {@link Object#hashCode() hashCode()} methods so it reverts to the default behavior for
16   * {@link Object} instead.
17   *
18   * <p>
19   * This allows us to (1) use {@link java.util.Collection#contains(Object)} to filter out unique
20   * instances when calculating object sizes and (2) call {@link Object#hashCode() hashCode()} without
21   * fear of an exception or infinite loop.
22   * </p>
23   *
24   * @see Instruments
25   */
26  class ObjectWrapper {
27  
28    /** The wrapped object. */
29    private final Object wrappedObject;
30  
31    /**
32     * Instantiates a new object wrapper.
33     *
34     * @param obj the obj
35     */
36    public ObjectWrapper(Object obj) {
37      this.wrappedObject = obj;
38    }
39  
40    @Override
41    public boolean equals(Object o1) {
42      if (wrappedObject == null) {
43        return o1 == null;
44      }
45      if (this.getClass() != o1.getClass()) {
46        return false;
47      }
48      ObjectWrapper ow = (ObjectWrapper) o1;
49      /*
50       * I know, this condition may seem strange, but if "equals" is left in, sizeOf() may run into an
51       * infinite loop on some objects
52       */
53      return ow.wrappedObject == wrappedObject; // || o.equals(ow.o);
54    }
55  
56    @Override
57    public int hashCode() {
58      return System.identityHashCode(wrappedObject);
59    }
60  
61  }