List of usage examples for java.lang.reflect Method getGenericParameterTypes
@Override
public Type[] getGenericParameterTypes()
From source file:org.openflexo.antar.binding.TypeUtils.java
private static boolean checkSucceed(Method m) { Type t1 = m.getGenericParameterTypes()[0]; Type t2 = m.getGenericParameterTypes()[1]; System.out.println("checkSucceed " + (isTypeAssignableFrom(t1, t2, true) ? "OK " : "NOK ") + "Method " + m.getName() + " t1: " + t1 + " of " + t1.getClass().getSimpleName() + " t2: " + t2 + " of " + t2.getClass().getSimpleName()); return isTypeAssignableFrom(t1, t2, true); }
From source file:org.jtester.utility.ReflectionUtils.java
/** * Returns all declared setter methods of fields of the given class that are * assignable from the given type.// w ww .j a v a2 s . c o m * * @param clazz * The class to get setters from, not null * @param type * The type, not null * @param isStatic * True if static setters are to be returned, false for * non-static * @return A list of Methods, empty list if none found */ public static Set<Method> getSettersAssignableFrom(Class<?> clazz, Type type, boolean isStatic) { Set<Method> settersAssignableFrom = new HashSet<Method>(); Set<Method> allMethods = getAllMethods(clazz); for (Method method : allMethods) { if (isSetter(method) && isAssignable(type, method.getGenericParameterTypes()[0]) && (isStatic == isStatic(method.getModifiers()))) { settersAssignableFrom.add(method); } } return settersAssignableFrom; }
From source file:io.neba.core.resourcemodels.factory.ModelInstantiator.java
/** * @return all public methods annotated with @Inject. Fails if a public method * annotated with @Inject does not take exactly one argument. *//* w w w . j av a2s .c o m*/ @Nonnull private static ModelServiceSetter[] resolveServiceSetters(@Nonnull Class<?> modelType) { List<ModelServiceSetter> serviceSetters = new ArrayList<>(); for (Method method : modelType.getMethods()) { if (isStatic(method.getModifiers())) { continue; } if (!annotations(method).containsName(INJECT_ANNOTATION_NAME)) { continue; } if (method.getParameterCount() != 1) { throw new InvalidModelException("The method " + method + " is annotated with @Inject and must thus take exactly one argument."); } Filter filter = findFilterAnnotation(method.getParameterAnnotations()[0]); Type serviceType = method.getGenericParameterTypes()[0]; ServiceDependency serviceDependency = new ServiceDependency(serviceType, modelType, filter); serviceSetters.add(new ModelServiceSetter(serviceDependency, method)); } return serviceSetters.toArray(new ModelServiceSetter[0]); }
From source file:eu.crisis_economics.abm.model.ModelUtils.java
/** * A depth first recursive parameter search tool. This function accepts an object * {@code X}, the ({@link String}) name {@code N} of a method, and a {@link Class} array * of method argument types. Any object in the configuration hierarchy of {@code X} which * has a method with with the appropriate signature and arguments is found and * returned.<br>/*from w w w. ja v a2 s. c o m*/ * * This search operates as follows: * * <ul> * <li> If {@code X} contains a method {@code N} with the specified arguments, then * store and remember this method; * <li> Otherwise search the subclasses of {@code X} for a method {@code N} with * the specified arguments. If such a method is found, then store and * remember this method; * <li> Apply the above steps recursively (depth first) to every field in {@code X} * of type {@link ComponentConfiguration}. Remember all of the methods identified * by this search process and return these methods as well as the object * instances in which they were found. * </ul> * * @param on * The object to search. * @param methodToFind * The method name to search for. * @param arguments * A list of {@link Class} argument types for the method to find. * @return * A {@link List} of {@link Pair}{@code s}. Each entry in this list is a {@link Pair} * composed of one {@link Method} object and one {@link Object}. The {@link Method} * satisfies the parameters of the query. The {@link Object} is an instance of an * object whose class possesses the {@link Method}. */ public static List<Pair<Method, Object>> search(final Object on, final String methodToFind, final Class<?>[] arguments) { final List<Pair<Method, Object>> result = new ArrayList<Pair<Method, Object>>(); final Class<?> parentType = on.getClass(); for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch .getSuperclass()) { Method methodPtr = null; try { // Try to find a method with the specified name and exact argument types: methodPtr = typeToSearch.getDeclaredMethod(methodToFind, arguments); result.add(Pair.create(methodPtr, on)); continue; } catch (final NoSuchMethodException e) { // Try to downcast method arguments for other class methods with the correct name: final Method[] allCalleeMethods = typeToSearch.getDeclaredMethods(); for (final Method method : allCalleeMethods) { if (!method.getName().equals(methodToFind)) continue; final Type[] argTypes = method.getGenericParameterTypes(); if (argTypes.length != arguments.length) continue; for (int j = 0; j < arguments.length; ++j) { if (!arguments[j].isAssignableFrom(argTypes[j].getClass())) continue; } methodPtr = method; result.add(Pair.create(methodPtr, on)); continue; } } if (methodPtr == null) continue; } // Search for any ComponentConfiguration fields in the specified object: for (Class<?> typeToSearch = parentType; typeToSearch != null; typeToSearch = typeToSearch .getSuperclass()) { for (Field field : typeToSearch.getDeclaredFields()) { if (!ComponentConfiguration.class.isAssignableFrom(field.getType())) continue; field.setAccessible(true); final Object instance; try { instance = field.get(on); } catch (final IllegalArgumentException e) { continue; // Not found } catch (final IllegalAccessException e) { continue; // Not found } if (instance != null) { final List<Pair<Method, Object>> subResult = search(instance, methodToFind, arguments); // Descend into fields if (subResult != null && !subResult.isEmpty()) result.addAll(subResult); else continue; } } } return result; }
From source file:org.gridgain.grid.util.json.GridJsonDeserializer.java
/** * Deserializes {@link JSONObject} to Java object of given class. * * @param obj Object for deserialization. * @param cls Class of resulted object./* w w w . ja v a 2 s . c om*/ * @return Deserialized object. * @throws GridException Thrown if any error occurs while deserialization. */ @SuppressWarnings("unchecked") private static Object buildObject(JSONObject obj, Class cls) throws GridException { assert obj != null; assert cls != null; Object res = newInstance(cls); Method[] mtds = cls.getMethods(); for (String key : (Set<String>) obj.keySet()) if (!isDescriptor(key)) { String mtdName = "set" + StringUtils.capitalize(key); for (Method mtd : mtds) if (mtd.getName().equals(mtdName) && mtd.getParameterTypes().length == 1) { Object param = deserialize(obj.get(key), mtd.getGenericParameterTypes()[0]); try { mtd.invoke(res, param); } catch (IllegalAccessException e) { throw new GridException("Can't set value " + param + " with method " + mtdName + " of class " + cls + ".", e); } catch (InvocationTargetException e) { throw new GridException("Can't set value " + param + " with method " + mtdName + " of class " + cls + ".", e); } break; } } return res; }
From source file:com.espertech.esper.util.MethodResolver.java
/** * Attempts to find the static or instance method described by the parameters, * or a method of the same name that will accept the same type of * parameters.//from w w w . jav a2s .c o m * @param declaringClass - the class to search for the method * @param methodName - the name of the method * @param paramTypes - the parameter types for the method * @param allowInstance - true to allow instance methods as well, false to allow only static method * @return - the Method object for this method * @throws EngineNoSuchMethodException if the method could not be found */ public static Method resolveMethod(Class declaringClass, String methodName, Class[] paramTypes, boolean allowInstance, boolean[] allowEventBeanType, boolean[] allowEventBeanCollType) throws EngineNoSuchMethodException { // Get all the methods for this class Method[] methods = declaringClass.getMethods(); Method bestMatch = null; int bestConversionCount = -1; // Examine each method, checking if the signature is compatible Method conversionFailedMethod = null; for (Method method : methods) { // Check the modifiers: we only want public and static, if required if (!isPublicAndStatic(method, allowInstance)) { continue; } // Check the name if (!method.getName().equals(methodName)) { continue; } // Check the parameter list int conversionCount = compareParameterTypesAllowContext(method.getParameterTypes(), paramTypes, allowEventBeanType, allowEventBeanCollType, method.getGenericParameterTypes()); // Parameters don't match if (conversionCount == -1) { conversionFailedMethod = method; continue; } // Parameters match exactly if (conversionCount == 0) { bestMatch = method; break; } // No previous match if (bestMatch == null) { bestMatch = method; bestConversionCount = conversionCount; } else { // Current match is better if (conversionCount < bestConversionCount) { bestMatch = method; bestConversionCount = conversionCount; } } } if (bestMatch != null) { logWarnBoxedToPrimitiveType(declaringClass, methodName, bestMatch, paramTypes); return bestMatch; } StringBuilder parameters = new StringBuilder(); if (paramTypes != null && paramTypes.length != 0) { String appendString = ""; for (Object param : paramTypes) { parameters.append(appendString); if (param == null) { parameters.append("(null)"); } else { parameters.append(param.toString()); } appendString = ", "; } } throw new EngineNoSuchMethodException( "Unknown method " + declaringClass.getSimpleName() + '.' + methodName + '(' + parameters + ')', conversionFailedMethod); }
From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java
/** * Injects via {@link DataBoundSetter}/*w w w . j a va 2 s.c o m*/ */ private static void injectSetters(Object o, Map<String, ?> arguments) throws Exception { for (Class<?> c = o.getClass(); c != null; c = c.getSuperclass()) { for (Field f : c.getDeclaredFields()) { if (f.isAnnotationPresent(DataBoundSetter.class)) { f.setAccessible(true); if (arguments.containsKey(f.getName())) { Object v = arguments.get(f.getName()); f.set(o, v != null ? coerce(c.getName() + "." + f.getName(), f.getType(), v) : null); } } } for (Method m : c.getDeclaredMethods()) { if (m.isAnnotationPresent(DataBoundSetter.class)) { Type[] parameterTypes = m.getGenericParameterTypes(); if (!m.getName().startsWith("set") || parameterTypes.length != 1) { throw new IllegalStateException(m + " cannot be a @DataBoundSetter"); } m.setAccessible(true); Object[] args = buildArguments(c, arguments, parameterTypes, new String[] { Introspector.decapitalize(m.getName().substring(3)) }, false); if (args != null) { m.invoke(o, args); } } } } }
From source file:com.laxser.blitz.web.paramresolver.ResolverFactoryImpl.java
private static Class<?>[] compileGenericParameterTypesDetail(Method method, int index) { Type genericParameterType = method.getGenericParameterTypes()[index]; ArrayList<Class<?>> typeDetailList = new ArrayList<Class<?>>(); if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); for (Type parameterArgType : parameterArgTypes) { if (parameterArgType instanceof Class) { typeDetailList.add((Class<?>) parameterArgType); } else { typeDetailList.add(String.class); }//from w w w .j a v a 2 s. c o m } Class<?>[] types = new Class[typeDetailList.size()]; typeDetailList.toArray(types); return types; } return null; }
From source file:org.gradle.internal.reflect.MethodSignatureEquivalence.java
@Override protected int doHash(Method method) { return new HashCodeBuilder().append(method.getName()).append(method.getGenericParameterTypes()) .toHashCode();/*from ww w. j a v a2 s . c o m*/ }
From source file:com.sawyer.advadapters.widget.JSONAdapter.java
/** * Determines whether the given method has he proper signature of a isFiltered method. * Specifically looking for the following: <ul><li>Name equals <i>"isFilteredOut"</i></li> * <li>Returns a primitive boolean</li> <li>Has exactly 2 parameters</li> <li>The 2nd param is a * CharSequence</li> </ul> If the method matches the criteria, the first parameter is extracted * and returned as a string to be used as a key in the filter cache. * * @param m Method to check signature of. * * @return String value of a filtered methods 1st parameter. Null if the method does not have * the proper signature./*from ww w . java 2 s. co m*/ */ private static String getFilterMethodKey(Method m) { if ("isFilteredOut".equals(m.getName()) && m.getGenericReturnType().equals(boolean.class)) { Type[] params = m.getGenericParameterTypes(); if (params.length == 2 && params[1].equals(CharSequence.class)) { String[] split = params[0].toString().split("\\s+"); return split[split.length - 1]; } } return null; }