Debian Codegraph @

src/main/java/org/jboss/classfilewriter/util/Signatures.java

raw
1 /*
2 * JBoss, Home of Professional Open Source.
3 *
4 * Copyright 2015 Red Hat, Inc.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.jboss.classfilewriter.util;
19
20 import static org.jboss.classfilewriter.util.DescriptorUtils.BOOLEAN_CLASS_DESCRIPTOR;
21 import static org.jboss.classfilewriter.util.DescriptorUtils.BYTE_CLASS_DESCRIPTOR;
22 import static org.jboss.classfilewriter.util.DescriptorUtils.CHAR_CLASS_DESCRIPTOR;
23 import static org.jboss.classfilewriter.util.DescriptorUtils.DOUBLE_CLASS_DESCRIPTOR;
24 import static org.jboss.classfilewriter.util.DescriptorUtils.FLOAT_CLASS_DESCRIPTOR;
25 import static org.jboss.classfilewriter.util.DescriptorUtils.INT_CLASS_DESCRIPTOR;
26 import static org.jboss.classfilewriter.util.DescriptorUtils.LONG_CLASS_DESCRIPTOR;
27 import static org.jboss.classfilewriter.util.DescriptorUtils.SHORT_CLASS_DESCRIPTOR;
28 import static org.jboss.classfilewriter.util.DescriptorUtils.VOID_CLASS_DESCRIPTOR;
29
30 import java.lang.reflect.GenericArrayType;
31 import java.lang.reflect.Method;
32 import java.lang.reflect.ParameterizedType;
33 import java.lang.reflect.Type;
34 import java.lang.reflect.TypeVariable;
35 import java.lang.reflect.WildcardType;
36
37 /**
38 * Encode signatures that use types outside the type system of the Java Virtual Machine. See also the JVM spec, section "4.7.9.1. Signatures".
39 *
40 * If anything goes wrong during encoding a {@link RuntimeException} is thrown.
41 *
42 * @author Martin Kouba
43 */
44 public final class Signatures {
45
46 static final char WILDCARD_UPPER_BOUND = '+';
47 static final char WILDCARD_LOWER_BOUND = '-';
48 static final char WILDCARD_NO_BOUND = '*';
49 static final char TYPE_PARAM_DEL_START = '<';
50 static final char TYPE_PARAM_DEL_END = '>';
51 static final char SEMICOLON = ';';
52 static final char COLON = ':';
53
54 private Signatures() {
55 }
56
57 /**
58 *
59 *
60 * @param method
61 * @return the JVM method signature
62 */
63 public static String methodSignature(Method method) {
64
65 StringBuilder builder = new StringBuilder();
66
67 // Type parameters
68 TypeVariable<?>[] typeParams = method.getTypeParameters();
69 if (typeParams.length > 0) {
70 builder.append(TYPE_PARAM_DEL_START);
71 for (TypeVariable<?> typeParam : typeParams) {
72 typeParameter(typeParam, builder);
73 }
74 builder.append(TYPE_PARAM_DEL_END);
75 }
76
77 // Formal parameters
78 Type[] params = method.getGenericParameterTypes();
79 builder.append('(');
80 if (params.length > 0) {
81 for (Type paramType : params) {
82 javaType(paramType, builder);
83 }
84 }
85 builder.append(')');
86
87 // Return type
88 javaType(method.getGenericReturnType(), builder);
89
90 // Throws
91 Type[] exceptions = method.getGenericExceptionTypes();
92 if (exceptions.length > 0) {
93 // "If the throws clause of a method or constructor declaration does not involve type variables, then a compiler may treat the declaration as having no throws clause for the purpose of emitting a method signature."
94 // Note that it's only possible to use a type parameter in a throws clause
95 for (Type exceptionType : exceptions) {
96 builder.append('^');
97 javaType(exceptionType, builder);
98 }
99 }
100 return builder.toString();
101 }
102
103 /**
104 * TypeParameter
105 *
106 * @param typeVariable
107 * @param builder
108 */
109 private static void typeParameter(TypeVariable<?> typeVariable, StringBuilder builder) {
110 builder.append(typeVariable.getName());
111 Type[] bounds = typeVariable.getBounds();
112 if (bounds.length > 0) {
113 for (int i = 0; i < bounds.length; i++) {
114 // If the first bound is an interface, add additional colon to comply with the spec (ClassBound is not optional)
115 if (i == 0 && getTypeParamBoundRawType(bounds[i]).isInterface()) {
116 builder.append(COLON);
117 }
118 builder.append(COLON);
119 javaType(bounds[i], builder);
120 }
121 } else {
122 // If no upper bound is declared, the upper bound is java.lang.Object
123 builder.append(COLON);
124 javaType(Object.class, builder);
125 }
126 }
127
128 /**
129 * JavaTypeSignature
130 *
131 * @param type
132 * @param builder
133 */
134 private static void javaType(Type type, StringBuilder builder) {
135 if (type instanceof Class) {
136 nonGenericType((Class<?>) type, builder);
137 } else if (type instanceof ParameterizedType) {
138 parameterizedType((ParameterizedType) type, builder);
139 } else if (type instanceof GenericArrayType) {
140 GenericArrayType genericArrayType = (GenericArrayType) type;
141 builder.append('[');
142 javaType(genericArrayType.getGenericComponentType(), builder);
143 } else if (type instanceof WildcardType) {
144 wildcardType((WildcardType) type, builder);
145 } else if (type instanceof TypeVariable) {
146 typeVariable((TypeVariable<?>) type, builder);
147 } else {
148 throw new IllegalArgumentException("Signature encoding error - unsupported type: " + type);
149 }
150 }
151
152 /**
153 * Note that Java language does not support more than one upper/lower bound.
154 *
155 * @param wildcard
156 * @param builder
157 */
158 private static void wildcardType(WildcardType wildcard, StringBuilder builder) {
159 if (wildcard.getLowerBounds().length > 0) {
160 for (Type lowerBound : wildcard.getLowerBounds()) {
161 builder.append(WILDCARD_LOWER_BOUND);
162 javaType(lowerBound, builder);
163 }
164 } else {
165 if (wildcard.getUpperBounds().length == 0 || (wildcard.getUpperBounds().length == 1 && Object.class.equals(wildcard.getUpperBounds()[0]))) {
166 // If no upper bound is explicitly declared, the upper bound is java.lang.Object
167 // It's not clear whether an empty array may be returned
168 builder.append(WILDCARD_NO_BOUND);
169 } else {
170 for (Type upperBound : wildcard.getUpperBounds()) {
171 builder.append(WILDCARD_UPPER_BOUND);
172 javaType(upperBound, builder);
173 }
174 }
175 }
176 }
177
178 private static void typeVariable(TypeVariable<?> typeVariable, StringBuilder builder) {
179 builder.append('T');
180 builder.append(typeVariable.getName());
181 builder.append(SEMICOLON);
182 }
183
184 private static void parameterizedType(ParameterizedType parameterizedType, StringBuilder builder) {
185 Type rawType = parameterizedType.getRawType();
186 if (rawType instanceof Class) {
187 builder.append(classTypeBase(((Class<?>) rawType).getName()));
188 } else {
189 throw new IllegalStateException(String.format("Signature encoding error - unsupported raw type: %s of parameterized type: %s", parameterizedType,
190 rawType));
191 }
192 builder.append(TYPE_PARAM_DEL_START);
193 for (Type actualTypeArgument : parameterizedType.getActualTypeArguments()) {
194 javaType(actualTypeArgument, builder);
195 }
196 builder.append(TYPE_PARAM_DEL_END);
197 builder.append(SEMICOLON);
198 }
199
200 /**
201 * BaseType, ClassTypeSignature or ArrayTypeSignature
202 *
203 * @param clazz
204 */
205 private static void nonGenericType(Class<?> clazz, StringBuilder builder) {
206 if (void.class.equals(clazz)) {
207 builder.append(VOID_CLASS_DESCRIPTOR);
208 } else if (byte.class.equals(clazz)) {
209 builder.append(BYTE_CLASS_DESCRIPTOR);
210 } else if (char.class.equals(clazz)) {
211 builder.append(CHAR_CLASS_DESCRIPTOR);
212 } else if (double.class.equals(clazz)) {
213 builder.append(DOUBLE_CLASS_DESCRIPTOR);
214 } else if (float.class.equals(clazz)) {
215 builder.append(FLOAT_CLASS_DESCRIPTOR);
216 } else if (int.class.equals(clazz)) {
217 builder.append(INT_CLASS_DESCRIPTOR);
218 } else if (long.class.equals(clazz)) {
219 builder.append(LONG_CLASS_DESCRIPTOR);
220 } else if (short.class.equals(clazz)) {
221 builder.append(SHORT_CLASS_DESCRIPTOR);
222 } else if (boolean.class.equals(clazz)) {
223 builder.append(BOOLEAN_CLASS_DESCRIPTOR);
224 } else if (clazz.isArray()) {
225 builder.append(encodeClassName(clazz.getName()));
226 } else {
227 builder.append(classTypeBase(clazz.getName()) + SEMICOLON);
228 }
229 }
230
231 /**
232 * ClassTypeSignature base
233 *
234 * @param clazz
235 * @param builder
236 */
237 private static String classTypeBase(String className) {
238 return 'L' + encodeClassName(className);
239 }
240
241 private static String encodeClassName(String className) {
242 return className.replace('.', '/');
243 }
244
245 @SuppressWarnings("unchecked")
246 private static <T> Class<T> getTypeParamBoundRawType(Type type) {
247 if (type instanceof Class<?>) {
248 return (Class<T>) type;
249 }
250 if (type instanceof ParameterizedType) {
251 if (((ParameterizedType) type).getRawType() instanceof Class<?>) {
252 return (Class<T>) ((ParameterizedType) type).getRawType();
253 }
254 }
255 if (type instanceof TypeVariable<?>) {
256 TypeVariable<?> variable = (TypeVariable<?>) type;
257 Type[] bounds = variable.getBounds();
258 return getBound(bounds);
259 }
260 throw new IllegalStateException("Signature encoding error - unexpected type parameter bound type: " + type);
261 }
262
263 @SuppressWarnings("unchecked")
264 private static <T> Class<T> getBound(Type[] bounds) {
265 if (bounds.length == 0) {
266 return (Class<T>) Object.class;
267 } else {
268 return getTypeParamBoundRawType(bounds[0]);
269 }
270 }
271
272 }