Skip to content

Package: ReflectionUtil$Wrapper

ReflectionUtil$Wrapper

nameinstructionbranchcomplexitylinemethod
wrap(Constructor[])
M: 29 C: 0
0%
M: 2 C: 0
0%
M: 2 C: 0
0%
M: 4 C: 0
0%
M: 1 C: 0
0%
wrap(Method[], String)
M: 34 C: 0
0%
M: 4 C: 0
0%
M: 3 C: 0
0%
M: 5 C: 0
0%
M: 1 C: 0
0%

Coverage

1: /*
2: * Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
3: *
4: * This program and the accompanying materials are made available under the
5: * terms of the Eclipse Public License v. 2.0, which is available at
6: * http://www.eclipse.org/legal/epl-2.0.
7: *
8: * This Source Code may also be made available under the following Secondary
9: * Licenses when the conditions for such availability set forth in the
10: * Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
11: * version 2 with the GNU Classpath Exception, which is available at
12: * https://www.gnu.org/software/classpath/license.html.
13: *
14: * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15: */
16:
17: package com.sun.el.util;
18:
19: import java.beans.IntrospectionException;
20: import java.beans.Introspector;
21: import java.beans.PropertyDescriptor;
22: import java.lang.reflect.Array;
23: import java.lang.reflect.Constructor;
24: import java.lang.reflect.InvocationTargetException;
25: import java.lang.reflect.Method;
26: import java.lang.reflect.Modifier;
27: import java.util.ArrayList;
28: import java.util.Arrays;
29: import java.util.Iterator;
30: import java.util.List;
31:
32: import jakarta.el.ELContext;
33: import jakarta.el.ELException;
34: import jakarta.el.MethodNotFoundException;
35: import jakarta.el.PropertyNotFoundException;
36:
37: import com.sun.el.lang.ELSupport;
38:
39: /**
40: * Utilities for Managing Serialization and Reflection
41: *
42: * @author Jacob Hookom [jacob@hookom.net]
43: * @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author: kchung $
44: */
45: public class ReflectionUtil {
46:
47: protected static final String[] EMPTY_STRING = new String[0];
48:
49: protected static final String[] PRIMITIVE_NAMES = new String[] { "boolean", "byte", "char", "double", "float", "int", "long", "short", "void" };
50:
51: protected static final Class[] PRIMITIVES = new Class[] { boolean.class, byte.class, char.class, double.class, float.class, int.class, long.class,
52: short.class, Void.TYPE };
53:
54: /**
55: *
56: */
57: private ReflectionUtil() {
58: super();
59: }
60:
61: public static Class forName(String name) throws ClassNotFoundException {
62: if (null == name || "".equals(name)) {
63: return null;
64: }
65: Class c = forNamePrimitive(name);
66: if (c == null) {
67: if (name.endsWith("[]")) {
68: String nc = name.substring(0, name.length() - 2);
69: c = Class.forName(nc, true, Thread.currentThread().getContextClassLoader());
70: c = Array.newInstance(c, 0).getClass();
71: } else {
72: c = Class.forName(name, true, Thread.currentThread().getContextClassLoader());
73: }
74: }
75: return c;
76: }
77:
78: protected static Class forNamePrimitive(String name) {
79: if (name.length() <= 8) {
80: int p = Arrays.binarySearch(PRIMITIVE_NAMES, name);
81: if (p >= 0) {
82: return PRIMITIVES[p];
83: }
84: }
85: return null;
86: }
87:
88: /**
89: * Converts an array of Class names to Class types
90: *
91: * @param s
92: * @return The array of Classes
93: * @throws ClassNotFoundException
94: */
95: public static Class[] toTypeArray(String[] s) throws ClassNotFoundException {
96: if (s == null) {
97: return null;
98: }
99: Class[] c = new Class[s.length];
100: for (int i = 0; i < s.length; i++) {
101: c[i] = forName(s[i]);
102: }
103: return c;
104: }
105:
106: /**
107: * Converts an array of Class types to Class names
108: *
109: * @param c
110: * @return The array of Classes
111: */
112: public static String[] toTypeNameArray(Class[] c) {
113: if (c == null) {
114: return null;
115: }
116: String[] s = new String[c.length];
117: for (int i = 0; i < c.length; i++) {
118: s[i] = c[i].getName();
119: }
120: return s;
121: }
122:
123: /**
124: * @param base The base object
125: * @param property The property
126: * @return The PropertyDescriptor for the base with the given property
127: * @throws ELException
128: * @throws PropertyNotFoundException
129: */
130: public static PropertyDescriptor getPropertyDescriptor(Object base, Object property) throws ELException, PropertyNotFoundException {
131: String name = ELSupport.coerceToString(property);
132: try {
133: PropertyDescriptor[] desc = Introspector.getBeanInfo(base.getClass()).getPropertyDescriptors();
134: for (int i = 0; i < desc.length; i++) {
135: if (desc[i].getName().equals(name)) {
136: return desc[i];
137: }
138: }
139: } catch (IntrospectionException ie) {
140: throw new ELException(ie);
141: }
142: throw new PropertyNotFoundException(MessageFactory.get("error.property.notfound", base, name));
143: }
144:
145: /*
146: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
147: */
148: public static Object invokeMethod(ELContext context, Method m, Object base, Object[] params) {
149:
150: Object[] parameters = buildParameters(context, m.getParameterTypes(), m.isVarArgs(), params);
151: try {
152: return m.invoke(base, parameters);
153: } catch (IllegalAccessException iae) {
154: throw new ELException(iae);
155: } catch (IllegalArgumentException iae) {
156: throw new ELException(iae);
157: } catch (InvocationTargetException ite) {
158: throw new ELException(ite.getCause());
159: }
160: }
161:
162: /*
163: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
164: */
165: public static Method findMethod(Class<?> clazz, String methodName, Class<?>[] paramTypes, Object[] paramValues) {
166:
167: if (clazz == null || methodName == null) {
168: throw new MethodNotFoundException(MessageFactory.get("error.method.notfound", clazz, methodName, paramString(paramTypes)));
169: }
170:
171: if (paramTypes == null) {
172: paramTypes = getTypesFromValues(paramValues);
173: }
174:
175: Method[] methods = clazz.getMethods();
176:
177: List<Wrapper> wrappers = Wrapper.wrap(methods, methodName);
178:
179: Wrapper result = findWrapper(clazz, wrappers, methodName, paramTypes, paramValues);
180:
181: if (result == null) {
182: return null;
183: }
184: return getMethod(clazz, (Method) result.unWrap());
185: }
186:
187: /*
188: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
189: */
190: private static Wrapper findWrapper(Class<?> clazz, List<Wrapper> wrappers, String name, Class<?>[] paramTypes, Object[] paramValues) {
191:
192: List<Wrapper> assignableCandidates = new ArrayList<Wrapper>();
193: List<Wrapper> coercibleCandidates = new ArrayList<Wrapper>();
194: List<Wrapper> varArgsCandidates = new ArrayList<Wrapper>();
195:
196: int paramCount;
197: if (paramTypes == null) {
198: paramCount = 0;
199: } else {
200: paramCount = paramTypes.length;
201: }
202:
203: for (Wrapper w : wrappers) {
204: Class<?>[] mParamTypes = w.getParameterTypes();
205: int mParamCount;
206: if (mParamTypes == null) {
207: mParamCount = 0;
208: } else {
209: mParamCount = mParamTypes.length;
210: }
211:
212: // Check the number of parameters
213: if (!(paramCount == mParamCount || (w.isVarArgs() && paramCount >= mParamCount - 1))) {
214: // Method has wrong number of parameters
215: continue;
216: }
217:
218: // Check the parameters match
219: boolean assignable = false;
220: boolean coercible = false;
221: boolean varArgs = false;
222: boolean noMatch = false;
223: for (int i = 0; i < mParamCount; i++) {
224: if (i == (mParamCount - 1) && w.isVarArgs()) {
225: varArgs = true;
226: // exact var array type match
227: if (mParamCount == paramCount) {
228: if (mParamTypes[i] == paramTypes[i]) {
229: continue;
230: }
231: }
232:
233: // unwrap the array's component type
234: Class<?> varType = mParamTypes[i].getComponentType();
235: for (int j = i; j < paramCount; j++) {
236: if (!isAssignableFrom(paramTypes[j], varType)
237: && !(paramValues != null && j < paramValues.length && isCoercibleFrom(paramValues[j], varType))) {
238: noMatch = true;
239: break;
240: }
241: }
242: } else if (mParamTypes[i].equals(paramTypes[i])) {
243: } else if (isAssignableFrom(paramTypes[i], mParamTypes[i])) {
244: assignable = true;
245: } else {
246: if (paramValues == null || i >= paramValues.length) {
247: noMatch = true;
248: break;
249: } else {
250: if (isCoercibleFrom(paramValues[i], mParamTypes[i])) {
251: coercible = true;
252: } else {
253: noMatch = true;
254: break;
255: }
256: }
257: }
258: }
259: if (noMatch) {
260: continue;
261: }
262:
263: if (varArgs) {
264: varArgsCandidates.add(w);
265: } else if (coercible) {
266: coercibleCandidates.add(w);
267: } else if (assignable) {
268: assignableCandidates.add(w);
269: } else {
270: // If a method is found where every parameter matches exactly,
271: // return it
272: return w;
273: }
274:
275: }
276:
277: String errorMsg = MessageFactory.get("error.method.ambiguous", clazz, name, paramString(paramTypes));
278: if (!assignableCandidates.isEmpty()) {
279: return findMostSpecificWrapper(assignableCandidates, paramTypes, false, errorMsg);
280: } else if (!coercibleCandidates.isEmpty()) {
281: return findMostSpecificWrapper(coercibleCandidates, paramTypes, true, errorMsg);
282: } else if (!varArgsCandidates.isEmpty()) {
283: return findMostSpecificWrapper(varArgsCandidates, paramTypes, true, errorMsg);
284: } else {
285: throw new MethodNotFoundException(MessageFactory.get("error.method.notfound", clazz, name, paramString(paramTypes)));
286: }
287:
288: }
289:
290: /*
291: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
292: */
293: private static Wrapper findMostSpecificWrapper(List<Wrapper> candidates, Class<?>[] matchingTypes, boolean elSpecific, String errorMsg) {
294: List<Wrapper> ambiguouses = new ArrayList<Wrapper>();
295: for (Wrapper candidate : candidates) {
296: boolean lessSpecific = false;
297:
298: Iterator<Wrapper> it = ambiguouses.iterator();
299: while (it.hasNext()) {
300: int result = isMoreSpecific(candidate, it.next(), matchingTypes, elSpecific);
301: if (result == 1) {
302: it.remove();
303: } else if (result == -1) {
304: lessSpecific = true;
305: }
306: }
307:
308: if (!lessSpecific) {
309: ambiguouses.add(candidate);
310: }
311: }
312:
313: if (ambiguouses.size() > 1) {
314: throw new MethodNotFoundException(errorMsg);
315: }
316:
317: return ambiguouses.get(0);
318: }
319:
320: /*
321: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
322: */
323: private static int isMoreSpecific(Wrapper wrapper1, Wrapper wrapper2, Class<?>[] matchingTypes, boolean elSpecific) {
324: Class<?>[] paramTypes1 = wrapper1.getParameterTypes();
325: Class<?>[] paramTypes2 = wrapper2.getParameterTypes();
326:
327: if (wrapper1.isVarArgs()) {
328: // JLS8 15.12.2.5 Choosing the Most Specific Method
329: int length = Math.max(Math.max(paramTypes1.length, paramTypes2.length), matchingTypes.length);
330: paramTypes1 = getComparingParamTypesForVarArgsMethod(paramTypes1, length);
331: paramTypes2 = getComparingParamTypesForVarArgsMethod(paramTypes2, length);
332:
333: if (length > matchingTypes.length) {
334: Class<?>[] matchingTypes2 = new Class<?>[length];
335: System.arraycopy(matchingTypes, 0, matchingTypes2, 0, matchingTypes.length);
336: matchingTypes = matchingTypes2;
337: }
338: }
339:
340: int result = 0;
341: for (int i = 0; i < paramTypes1.length; i++) {
342: if (paramTypes1[i] != paramTypes2[i]) {
343: int r2 = isMoreSpecific(paramTypes1[i], paramTypes2[i], matchingTypes[i], elSpecific);
344: if (r2 == 1) {
345: if (result == -1) {
346: return 0;
347: }
348: result = 1;
349: } else if (r2 == -1) {
350: if (result == 1) {
351: return 0;
352: }
353: result = -1;
354: } else {
355: return 0;
356: }
357: }
358: }
359:
360: if (result == 0) {
361: // The nature of bridge methods is such that it actually
362: // doesn't matter which one we pick as long as we pick
363: // one. That said, pick the 'right' one (the non-bridge
364: // one) anyway.
365: result = Boolean.compare(wrapper1.isBridge(), wrapper2.isBridge());
366: }
367:
368: return result;
369: }
370:
371: /*
372: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
373: */
374: private static int isMoreSpecific(Class<?> type1, Class<?> type2, Class<?> matchingType, boolean elSpecific) {
375: type1 = getBoxingTypeIfPrimitive(type1);
376: type2 = getBoxingTypeIfPrimitive(type2);
377: if (type2.isAssignableFrom(type1)) {
378: return 1;
379: } else if (type1.isAssignableFrom(type2)) {
380: return -1;
381: } else {
382: if (elSpecific) {
383: /*
384: * Number will be treated as more specific
385: *
386: * ASTInteger only return Long or BigInteger, no Byte / Short / Integer. ASTFloatingPoint also.
387: *
388: */
389: if (matchingType != null && Number.class.isAssignableFrom(matchingType)) {
390: boolean b1 = Number.class.isAssignableFrom(type1) || type1.isPrimitive();
391: boolean b2 = Number.class.isAssignableFrom(type2) || type2.isPrimitive();
392: if (b1 && !b2) {
393: return 1;
394: } else if (b2 && !b1) {
395: return -1;
396: } else {
397: return 0;
398: }
399: }
400:
401: return 0;
402: } else {
403: return 0;
404: }
405: }
406: }
407:
408: /*
409: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
410: */
411: private static Class<?> getBoxingTypeIfPrimitive(Class<?> clazz) {
412: if (clazz.isPrimitive()) {
413: if (clazz == Boolean.TYPE) {
414: return Boolean.class;
415: } else if (clazz == Character.TYPE) {
416: return Character.class;
417: } else if (clazz == Byte.TYPE) {
418: return Byte.class;
419: } else if (clazz == Short.TYPE) {
420: return Short.class;
421: } else if (clazz == Integer.TYPE) {
422: return Integer.class;
423: } else if (clazz == Long.TYPE) {
424: return Long.class;
425: } else if (clazz == Float.TYPE) {
426: return Float.class;
427: } else {
428: return Double.class;
429: }
430: } else {
431: return clazz;
432: }
433:
434: }
435:
436: /*
437: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
438: */
439: private static Class<?>[] getComparingParamTypesForVarArgsMethod(Class<?>[] paramTypes, int length) {
440: Class<?>[] result = new Class<?>[length];
441: System.arraycopy(paramTypes, 0, result, 0, paramTypes.length - 1);
442: Class<?> type = paramTypes[paramTypes.length - 1].getComponentType();
443: for (int i = paramTypes.length - 1; i < length; i++) {
444: result[i] = type;
445: }
446:
447: return result;
448: }
449:
450: /*
451: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
452: */
453: private static final String paramString(Class<?>[] types) {
454: if (types != null) {
455: StringBuilder sb = new StringBuilder();
456: for (int i = 0; i < types.length; i++) {
457: if (types[i] == null) {
458: sb.append("null, ");
459: } else {
460: sb.append(types[i].getName()).append(", ");
461: }
462: }
463: if (sb.length() > 2) {
464: sb.setLength(sb.length() - 2);
465: }
466: return sb.toString();
467: }
468: return null;
469: }
470:
471: /*
472: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
473: */
474: static boolean isAssignableFrom(Class<?> src, Class<?> target) {
475: // src will always be an object
476: // Short-cut. null is always assignable to an object and in EL null
477: // can always be coerced to a valid value for a primitive
478: if (src == null) {
479: return true;
480: }
481:
482: target = getBoxingTypeIfPrimitive(target);
483:
484: return target.isAssignableFrom(src);
485: }
486:
487: /*
488: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
489: */
490: private static boolean isCoercibleFrom(Object src, Class<?> target) {
491: // TODO: This isn't pretty but it works. Significant refactoring would
492: // be required to avoid the exception.
493: try {
494: ELSupport.coerceToType(src, target);
495: } catch (Exception e) {
496: return false;
497: }
498: return true;
499: }
500:
501: /*
502: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
503: */
504: private static Class<?>[] getTypesFromValues(Object[] values) {
505: if (values == null) {
506: return null;
507: }
508:
509: Class<?> result[] = new Class<?>[values.length];
510: for (int i = 0; i < values.length; i++) {
511: if (values[i] == null) {
512: result[i] = null;
513: } else {
514: result[i] = values[i].getClass();
515: }
516: }
517: return result;
518: }
519:
520: /*
521: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
522: *
523: * Get a public method form a public class or interface of a given method. Note that if a PropertyDescriptor is obtained
524: * for a non-public class that implements a public interface, the read/write methods will be for the class, and
525: * therefore inaccessible. To correct this, a version of the same method must be found in a superclass or interface.
526: *
527: */
528: static Method getMethod(Class<?> type, Method m) {
529: if (m == null || Modifier.isPublic(type.getModifiers())) {
530: return m;
531: }
532: Class<?>[] inf = type.getInterfaces();
533: Method mp = null;
534: for (int i = 0; i < inf.length; i++) {
535: try {
536: mp = inf[i].getMethod(m.getName(), m.getParameterTypes());
537: mp = getMethod(mp.getDeclaringClass(), mp);
538: if (mp != null) {
539: return mp;
540: }
541: } catch (NoSuchMethodException e) {
542: // Ignore
543: }
544: }
545: Class<?> sup = type.getSuperclass();
546: if (sup != null) {
547: try {
548: mp = sup.getMethod(m.getName(), m.getParameterTypes());
549: mp = getMethod(mp.getDeclaringClass(), mp);
550: if (mp != null) {
551: return mp;
552: }
553: } catch (NoSuchMethodException e) {
554: // Ignore
555: }
556: }
557: return null;
558: }
559:
560: /*
561: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
562: */
563: static Constructor<?> getConstructor(Class<?> type, Constructor<?> c) {
564: if (c == null || Modifier.isPublic(type.getModifiers())) {
565: return c;
566: }
567: Constructor<?> cp = null;
568: Class<?> sup = type.getSuperclass();
569: if (sup != null) {
570: try {
571: cp = sup.getConstructor(c.getParameterTypes());
572: cp = getConstructor(cp.getDeclaringClass(), cp);
573: if (cp != null) {
574: return cp;
575: }
576: } catch (NoSuchMethodException e) {
577: // Ignore
578: }
579: }
580: return null;
581: }
582:
583: /*
584: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
585: */
586: static Object[] buildParameters(ELContext context, Class<?>[] parameterTypes, boolean isVarArgs, Object[] params) {
587: Object[] parameters = null;
588: if (parameterTypes.length > 0) {
589: parameters = new Object[parameterTypes.length];
590: int paramCount = params == null ? 0 : params.length;
591: if (isVarArgs) {
592: int varArgIndex = parameterTypes.length - 1;
593: // First argCount-1 parameters are standard
594: for (int i = 0; (i < varArgIndex && i < paramCount); i++) {
595: parameters[i] = context.convertToType(params[i], parameterTypes[i]);
596: }
597: // Last parameter is the varargs
598: if (parameterTypes.length == paramCount && parameterTypes[varArgIndex] == params[varArgIndex].getClass()) {
599: parameters[varArgIndex] = params[varArgIndex];
600: } else {
601: Class<?> varArgClass = parameterTypes[varArgIndex].getComponentType();
602: final Object varargs = Array.newInstance(varArgClass, (paramCount - varArgIndex));
603: for (int i = (varArgIndex); i < paramCount; i++) {
604: Array.set(varargs, i - varArgIndex, context.convertToType(params[i], varArgClass));
605: }
606: parameters[varArgIndex] = varargs;
607: }
608: } else {
609: for (int i = 0; i < parameterTypes.length && i < paramCount; i++) {
610: parameters[i] = context.convertToType(params[i], parameterTypes[i]);
611: }
612: }
613: }
614: return parameters;
615: }
616:
617: /*
618: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
619: */
620: private abstract static class Wrapper {
621:
622: public static List<Wrapper> wrap(Method[] methods, String name) {
623: List<Wrapper> result = new ArrayList<>();
624:• for (Method method : methods) {
625:• if (method.getName().equals(name)) {
626: result.add(new MethodWrapper(method));
627: }
628: }
629: return result;
630: }
631:
632: public static List<Wrapper> wrap(Constructor<?>[] constructors) {
633: List<Wrapper> result = new ArrayList<>();
634:• for (Constructor<?> constructor : constructors) {
635: result.add(new ConstructorWrapper(constructor));
636: }
637: return result;
638: }
639:
640: public abstract Object unWrap();
641:
642: public abstract Class<?>[] getParameterTypes();
643:
644: public abstract boolean isVarArgs();
645:
646: public abstract boolean isBridge();
647: }
648:
649: /*
650: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
651: */
652: private static class MethodWrapper extends Wrapper {
653: private final Method m;
654:
655: public MethodWrapper(Method m) {
656: this.m = m;
657: }
658:
659: @Override
660: public Object unWrap() {
661: return m;
662: }
663:
664: @Override
665: public Class<?>[] getParameterTypes() {
666: return m.getParameterTypes();
667: }
668:
669: @Override
670: public boolean isVarArgs() {
671: return m.isVarArgs();
672: }
673:
674: @Override
675: public boolean isBridge() {
676: return m.isBridge();
677: }
678: }
679:
680: /*
681: * This method duplicates code in jakarta.el.ELUtil. When making changes keep the code in sync.
682: */
683: private static class ConstructorWrapper extends Wrapper {
684: private final Constructor<?> c;
685:
686: public ConstructorWrapper(Constructor<?> c) {
687: this.c = c;
688: }
689:
690: @Override
691: public Object unWrap() {
692: return c;
693: }
694:
695: @Override
696: public Class<?>[] getParameterTypes() {
697: return c.getParameterTypes();
698: }
699:
700: @Override
701: public boolean isVarArgs() {
702: return c.isVarArgs();
703: }
704:
705: @Override
706: public boolean isBridge() {
707: return false;
708: }
709: }
710:
711: }