/** * Creates new field descriptor and resolve all additional field data. Also, forces access to a * field. */ public FieldDescriptor(ClassDescriptor classDescriptor, Field field) { super(classDescriptor, ReflectUtil.isPublic(field)); this.field = field; this.type = field.getGenericType(); this.rawType = ReflectUtil.getRawType(type, classDescriptor.getType()); this.rawComponentType = ReflectUtil.getComponentType(type, classDescriptor.getType()); this.rawKeyComponentType = ReflectUtil.getComponentType(type, classDescriptor.getType(), 0); ReflectUtil.forceAccess(field); }
protected ActionRequest createActionRequest(String actionPath) { HttpServletRequest servletRequest = mock(HttpServletRequest.class); HttpServletResponse servletResponse = mock(HttpServletResponse.class); HttpSession httpSession = mock(HttpSession.class); ServletContext servletContext = mock(ServletContext.class); when(servletRequest.getSession()).thenReturn(httpSession); when(httpSession.getServletContext()).thenReturn(servletContext); MadvocController madvocController = new MadvocController(); Object action = new Object(); ActionInfo actionInfo = new ActionInfo( Action.class, ReflectUtil.findMethod(Action.class, "view"), null, null, new ActionDef(actionPath, "GET"), null, false, null, null); return new ActionRequest( madvocController, actionInfo.getActionPath(), actionInfo, action, servletRequest, servletResponse); }
@Override public MethodAction createActionIfPossible(String actionName) { // will resolve if both a class and method name can be parsed, and a valid class with that // method name can be loaded String methodName = MethodAction.methodNameForAction(actionName); String className = MethodAction.classNameForAction(actionName); if (StringUtils.isEmpty(methodName) || StringUtils.isEmpty(className)) { return null; } try { Class<?> clazz = Class.forName(className); // TODO - Restricted in GAE - why is this better? // ClassLoaderUtil.loadClass(className); Method method = ReflectUtil.findMethod(clazz, methodName); if (method == null) { return null; } MethodAction methodAction = new MethodAction(clazz, method, findInterceptors(method)); // force instantiation of controller - this allows controllers to be injected into eachother // and also flushes out instantiation issues at startup Object controller = createController(methodAction); controllerInstances.put(methodAction.type(), controller); return methodAction; } catch (BaseException e) { throw e; } catch (Exception e) { return null; } }
/** * Creates new instance for current property name through its setter. It uses default constructor! */ protected Object createBeanProperty(BeanProperty bp) { MethodDescriptor setter = bp.cd.getBeanSetterMethodDescriptor(bp.name, true); FieldDescriptor field = null; Class type; if (setter != null) { type = setter.getRawParameterTypes()[0]; } else { field = getField(bp, true); if (field == null) { return null; } type = field.getRawType(); } Object newInstance; try { newInstance = ReflectUtil.newInstance(type); } catch (Exception ex) { throw new BeanException("Unable to create property: " + bp.name, bp, ex); } if (setter != null) { invokeSetter(bp.bean, setter, newInstance); } else { setFieldValue(bp.bean, field, newInstance); } return newInstance; }
/** * Adds the content pointed by the URL to the classpath during runtime. Uses reflection since * <code>addURL</code> method of <code>URLClassLoader</code> is protected. */ public static void addUrlToClassPath(URL url, ClassLoader classLoader) { try { ReflectUtil.invokeDeclared( URLClassLoader.class, classLoader, "addURL", new Class[] {URL.class}, new Object[] {url}); } catch (Exception ex) { throw new IllegalArgumentException("Add URL failed: " + url, ex); } }
/** * Returns default class loader. By default, it is {@link #getContextClassLoader() threads context * class loader}. If this one is <code>null</code>, then class loader of the <b>caller class</b> * is returned. */ public static ClassLoader getDefaultClassLoader() { ClassLoader cl = getContextClassLoader(); if (cl == null) { Class callerClass = ReflectUtil.getCallerClass(2); cl = callerClass.getClassLoader(); } return cl; }
@Test public void testPrimitivesArrays1() throws NoSuchMethodException { Method m = ReflectUtil.findDeclaredMethod(Foo.class, "primarr1"); MethodParameter[] mps = Paramo.resolveParameters(m); String[] s = resolveParameterNames(mps); assertEquals(2, s.length); assertEquals("one", s[0]); assertEquals("two", s[1]); }
@Test public void testGeneric() { Method m = ReflectUtil.findDeclaredMethod(Generic.class, "one"); MethodParameter[] mps = Paramo.resolveParameters(m); assertEquals(2, mps.length); assertEquals("foo", mps[0].getName()); assertEquals("Ljava/util/Map<Ljava/lang/String;Ljava/lang/Long;>;", mps[0].getSignature()); assertEquals("aLong", mps[1].getName()); assertEquals("Ljava/lang/Long;", mps[1].getSignature()); m = ReflectUtil.findDeclaredMethod(Generic.class, "two"); mps = Paramo.resolveParameters(m); assertEquals(1, mps.length); assertEquals("zzz", mps[0].getName()); assertEquals( "Ljava/util/Map<Ljava/lang/String;Ljodd/paramo/data/Bar<Ljava/lang/Long;>;>;", mps[0].getSignature()); }
public ClassDescriptor( Class type, boolean scanAccessible, boolean extendedProperties, boolean includeFieldsAsProperties, String propertyFieldPrefix) { this.type = type; this.scanAccessible = scanAccessible; this.extendedProperties = extendedProperties; this.includeFieldsAsProperties = includeFieldsAsProperties; this.propertyFieldPrefix = propertyFieldPrefix; isArray = type.isArray(); isMap = ReflectUtil.isSubclass(type, Map.class); isList = ReflectUtil.isSubclass(type, List.class); isSet = ReflectUtil.isSubclass(type, Set.class); isCollection = ReflectUtil.isSubclass(type, Collection.class); }
@Test public void testPrimitivesArrays3() throws NoSuchMethodException { Method m = ReflectUtil.findDeclaredMethod(Foo.class, "primarrShortByte"); MethodParameter[] mps = Paramo.resolveParameters(m); String[] s = resolveParameterNames(mps); assertEquals(3, s.length); assertEquals("s", s[0]); assertEquals("y", s[1]); assertEquals("somethingElse", s[2]); }
@Test public void testNonGeneric() { Method m = ReflectUtil.findDeclaredMethod(NonGeneric.class, "one"); MethodParameter[] mps = Paramo.resolveParameters(m); assertEquals(2, mps.length); assertEquals("foo", mps[0].getName()); assertEquals("Ljava/util/Map;", mps[0].getSignature()); assertEquals("aLong", mps[1].getName()); assertEquals("Ljava/lang/Long;", mps[1].getSignature()); }
@Test public void testPrimitivesArrays2() throws NoSuchMethodException { Method m = ReflectUtil.findDeclaredMethod(Foo.class, "primarr2"); MethodParameter[] mps = Paramo.resolveParameters(m); String[] s = resolveParameterNames(mps); assertEquals(6, s.length); assertEquals("i", s[0]); assertEquals("l", s[1]); assertEquals("f", s[2]); assertEquals("d", s[3]); assertEquals("b", s[4]); assertEquals("c", s[5]); }
/** * Loads a class with a given name dynamically, more reliable then <code>Class.forName</code>. * * <p>Class will be loaded using class loaders in the following order: * * <ul> * <li>provided class loader (if any) * <li><code>Thread.currentThread().getContextClassLoader()}</code> * <li>caller classloader * <li>using <code>Class.forName</code> * </ul> */ public static Class loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { className = prepareClassnameForLoading(className); if ((className.indexOf('.') == -1) || (className.indexOf('[') == -1)) { // maybe a primitive int primitiveNdx = getPrimitiveClassNameIndex(className); if (primitiveNdx >= 0) { return PRIMITIVE_TYPES[primitiveNdx]; } } // try #1 - using provided class loader try { if (classLoader != null) { return classLoader.loadClass(className); } } catch (ClassNotFoundException ignore) { } // try #2 - using thread class loader ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader(); if ((currentThreadClassLoader != null) && (currentThreadClassLoader != classLoader)) { try { return currentThreadClassLoader.loadClass(className); } catch (ClassNotFoundException ignore) { } } // try #3 - using caller classloader, similar as Class.forName() Class callerClass = ReflectUtil.getCallerClass(2); ClassLoader callerClassLoader = callerClass.getClassLoader(); if ((callerClassLoader != classLoader) && (callerClassLoader != currentThreadClassLoader)) { try { return callerClassLoader.loadClass(className); } catch (ClassNotFoundException ignore) { } } // try #4 - using Class.forName(). We must use this since for JDK >= 6 // arrays will be not loaded using classloader, but only with forName. try { return Class.forName(className); } catch (ClassNotFoundException ignore) { } throw new ClassNotFoundException("Class not found: " + className); }
/** * Finds and loads class on classpath even if it was already loaded. * * @param className class name to find * @param classPath classpath * @param parent optional parent class loader, may be <code>null</code> */ public static Class findClass(String className, URL[] classPath, ClassLoader parent) { URLClassLoader tempClassLoader = parent != null ? new URLClassLoader(classPath, parent) : new URLClassLoader(classPath); try { return (Class) ReflectUtil.invokeDeclared( URLClassLoader.class, tempClassLoader, "findClass", new Class[] {String.class}, new Object[] {className}); } catch (Throwable th) { throw new RuntimeException("Class not found: " + className, th); } }
/** * Defines a class from byte array into the specified class loader. Warning: this is a * <b>hack</b>! * * @param className optional class name, may be <code>null</code> * @param classData bytecode data * @param classLoader classloader that will load class */ public static Class defineClass(String className, byte[] classData, ClassLoader classLoader) { try { return (Class) ReflectUtil.invokeDeclared( ClassLoader.class, classLoader, "defineClass", new Class[] {String.class, byte[].class, int.class, int.class}, new Object[] { className, classData, Integer.valueOf(0), Integer.valueOf(classData.length) }); } catch (Throwable th) { throw new RuntimeException("Define class failed: " + className, th); } }
/** * Returns the element of an array forced. If value is <code>null</code>, it will be instantiated. * If not the last part of indexed bean property, array will be expanded to the index if * necessary. */ protected Object arrayForcedGet(BeanProperty bp, Object array, int index) { Class componentType = array.getClass().getComponentType(); if (bp.last == false) { array = ensureArraySize(bp, array, componentType, index); } Object value = Array.get(array, index); if (value == null) { try { value = ReflectUtil.newInstance(componentType); } catch (Exception ex) { throw new BeanException( "Unable to create array element: " + bp.name + '[' + index + ']', bp, ex); } Array.set(array, index, value); } return value; }
/** * Retrieves given resource as URL. Resource is always absolute and may starts with a slash * character. * * <p>Resource will be loaded using class loaders in the following order: * * <ul> * <li>{@link Thread#getContextClassLoader() Thread.currentThread().getContextClassLoader()} * <li>{@link Class#getClassLoader() ClassLoaderUtil.class.getClassLoader()} * <li>if <code>callingClass</code> is provided: {@link Class#getClassLoader() * callingClass.getClassLoader()} * </ul> */ public static URL getResourceUrl(String resourceName, ClassLoader classLoader) { if (resourceName.startsWith("/")) { resourceName = resourceName.substring(1); } URL resourceUrl; // try #1 - using provided class loader if (classLoader != null) { resourceUrl = classLoader.getResource(resourceName); if (resourceUrl != null) { return resourceUrl; } } // try #2 - using thread class loader ClassLoader currentThreadClassLoader = Thread.currentThread().getContextClassLoader(); if ((currentThreadClassLoader != null) && (currentThreadClassLoader != classLoader)) { resourceUrl = currentThreadClassLoader.getResource(resourceName); if (resourceUrl != null) { return resourceUrl; } } // try #3 - using caller classloader, similar as Class.forName() Class callerClass = ReflectUtil.getCallerClass(2); ClassLoader callerClassLoader = callerClass.getClassLoader(); if ((callerClassLoader != classLoader) && (callerClassLoader != currentThreadClassLoader)) { resourceUrl = callerClassLoader.getResource(resourceName); if (resourceUrl != null) { return resourceUrl; } } return null; }
/** Resolves raw component type for given index. This value is NOT cached. */ public Class resolveRawComponentType(int index) { return ReflectUtil.getComponentType(type, classDescriptor.getType(), index); }