View Javadoc
1   /*
2    * MIT License
3    * Copyright (c) 2006-2025 JMockit developers
4    * See LICENSE file for full license text.
5    */
6   package mockit.asm.types;
7   
8   import edu.umd.cs.findbugs.annotations.NonNull;
9   
10  import org.checkerframework.checker.index.qual.NonNegative;
11  
12  public final class ArrayType extends ReferenceType {
13      @NonNull
14      public static ArrayType create(@NonNull String typeDesc) {
15          return new ArrayType(typeDesc.toCharArray());
16      }
17  
18      /**
19       * Initializes an array type.
20       *
21       * @param typeDesc
22       *            a buffer containing the descriptor of the array type
23       * @param off
24       *            the offset of the descriptor in the buffer
25       */
26      @NonNull
27      static ArrayType create(@NonNull char[] typeDesc, @NonNegative int off) {
28          int len = findNumberOfDimensions(typeDesc, off);
29  
30          if (typeDesc[off + len] == 'L') {
31              len = findTypeNameLength(typeDesc, off, len);
32          }
33  
34          return new ArrayType(typeDesc, off, len + 1);
35      }
36  
37      @NonNegative
38      private static int findNumberOfDimensions(@NonNull char[] typeDesc, @NonNegative int off) {
39          int dimensions = 1;
40  
41          while (typeDesc[off + dimensions] == '[') {
42              dimensions++;
43          }
44  
45          return dimensions;
46      }
47  
48      private ArrayType(@NonNull char[] typeDesc, @NonNegative int off, @NonNegative int len) {
49          super(typeDesc, off, len);
50      }
51  
52      ArrayType(@NonNull char[] typeDesc) {
53          super(typeDesc);
54      }
55  
56      /**
57       * Returns the number of dimensions of this array type.
58       */
59      @NonNegative
60      public int getDimensions() {
61          return findNumberOfDimensions(typeDescChars, off);
62      }
63  
64      /**
65       * Returns the type of the elements of this array type.
66       */
67      @NonNull
68      public JavaType getElementType() {
69          int dimensions = getDimensions();
70          return getType(typeDescChars, off + dimensions);
71      }
72  
73      @NonNull
74      @Override
75      public String getClassName() {
76          String className = getElementType().getClassName();
77          StringBuilder sb = new StringBuilder(className);
78          int dimensions = getDimensions();
79  
80          for (int i = dimensions; i > 0; i--) {
81              sb.append("[]");
82          }
83  
84          return sb.toString();
85      }
86  }