View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.dbcp2.datasources;
19  
20  import java.util.Arrays;
21  import java.util.Objects;
22  
23  import org.apache.commons.dbcp2.Utils;
24  
25  /**
26   * A {@code char} array wrapper that does not reveal its contents inadvertently through toString(). In contrast to, for
27   * example, AtomicReference which toString()'s its contents.
28   *
29   * May contain null.
30   *
31   * @since 2.9.0
32   */
33  final class CharArray {
34  
35      static final CharArrayatasources/CharArray.html#CharArray">CharArray NULL = new CharArray((char[]) null);
36  
37      private final char[] chars;
38  
39      CharArray(final char[] chars) {
40          this.chars = Utils.clone(chars);
41      }
42  
43      CharArray(final String string) {
44          this.chars = Utils.toCharArray(string);
45      }
46  
47      /**
48       * Converts the value of char array as a String.
49       *
50       * @return value as a string, may be null.
51       */
52      String asString() {
53          return Utils.toString(chars);
54      }
55  
56      @Override
57      public boolean equals(final Object obj) {
58          if (this == obj) {
59              return true;
60          }
61          if (!(obj instanceof CharArray)) {
62              return false;
63          }
64          final CharArray/../../../../org/apache/commons/dbcp2/datasources/CharArray.html#CharArray">CharArray other = (CharArray) obj;
65          return Arrays.equals(chars, other.chars);
66      }
67  
68      /**
69       * Gets the value of char array.
70       *
71       * @return value, may be null.
72       */
73      char[] get() {
74          return chars == null ? null : chars.clone();
75      }
76  
77      @Override
78      public int hashCode() {
79          return Objects.hash(Arrays.hashCode(chars));
80      }
81  
82      /**
83       * Calls {@code super.toString()} and does not reveal its contents inadvertently.
84       */
85      @Override
86      public String toString() {
87          return super.toString();
88      }
89  }