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.internal.util;
7   
8   import edu.umd.cs.findbugs.annotations.NonNull;
9   
10  import mockit.asm.types.ArrayType;
11  import mockit.asm.types.JavaType;
12  import mockit.asm.types.PrimitiveType;
13  
14  public final class TypeDescriptor {
15      private static final Class<?>[] NO_PARAMETERS = {};
16  
17      private TypeDescriptor() {
18      }
19  
20      @NonNull
21      public static Class<?>[] getParameterTypes(@NonNull String methodDesc) {
22          JavaType[] paramTypes = JavaType.getArgumentTypes(methodDesc);
23  
24          if (paramTypes.length == 0) {
25              return NO_PARAMETERS;
26          }
27  
28          Class<?>[] paramClasses = new Class<?>[paramTypes.length];
29  
30          for (int i = 0; i < paramTypes.length; i++) {
31              paramClasses[i] = getClassForType(paramTypes[i]);
32          }
33  
34          return paramClasses;
35      }
36  
37      @NonNull
38      public static Class<?> getReturnType(@NonNull String methodSignature) {
39          String methodDesc = methodDescriptionWithoutTypeArguments(methodSignature);
40          JavaType returnType = JavaType.getReturnType(methodDesc);
41          return getClassForType(returnType);
42      }
43  
44      @NonNull
45      private static String methodDescriptionWithoutTypeArguments(@NonNull String methodSignature) {
46          while (true) {
47              int p = methodSignature.indexOf('<');
48  
49              if (p < 0) {
50                  return methodSignature;
51              }
52  
53              String firstPart = methodSignature.substring(0, p);
54              int q = methodSignature.indexOf('>', p) + 1;
55  
56              if (methodSignature.charAt(q) == '.') { // in case there is an inner class
57                  methodSignature = firstPart + '$' + methodSignature.substring(q + 1);
58              } else {
59                  methodSignature = firstPart + methodSignature.substring(q);
60              }
61          }
62      }
63  
64      @NonNull
65      public static Class<?> getClassForType(@NonNull JavaType type) {
66          if (type instanceof PrimitiveType) {
67              return ((PrimitiveType) type).getType();
68          }
69  
70          String className;
71  
72          if (type instanceof ArrayType) {
73              className = type.getDescriptor().replace('/', '.');
74          } else {
75              className = type.getClassName();
76          }
77  
78          return ClassLoad.loadClass(className);
79      }
80  }