List of usage examples for java.lang.reflect Method getGenericParameterTypes
@Override
public Type[] getGenericParameterTypes()
From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java
/** * this method generate record instance by calling newIntance * using reflection, add register the generated value to typeValueCache */// w w w .j a va2 s.c o m @SuppressWarnings("rawtypes") private static Object generateByNewInstance(Class clazz) throws Exception { Object ret = typeValueCache.get(clazz); if (ret != null) { return ret; } Method newInstance = null; Type[] paramTypes = new Type[0]; // get newInstance method with most parameters for (Method m : clazz.getMethods()) { int mod = m.getModifiers(); if (m.getDeclaringClass().equals(clazz) && Modifier.isPublic(mod) && Modifier.isStatic(mod) && m.getName().equals("newInstance")) { Type[] pts = m.getGenericParameterTypes(); if (newInstance == null || (pts.length > paramTypes.length)) { newInstance = m; paramTypes = pts; } } } if (newInstance == null) { throw new IllegalArgumentException("type " + clazz.getName() + " does not have newInstance method"); } Object[] args = new Object[paramTypes.length]; for (int i = 0; i < args.length; i++) { args[i] = genTypeValue(paramTypes[i]); } ret = newInstance.invoke(null, args); typeValueCache.put(clazz, ret); return ret; }
From source file:GenericClass.java
/** * Return real, "generics dereferenced", parameter types for the given method. * //from w ww.ja v a2 s . c o m * @param method * The method to analyze * @return The real classes, dereferencing generics */ public GenericClass[] getParameterTypes(Method method) { Class<?> declaring = method.getDeclaringClass(); String declname = declaring.getName(); Type[] parameterTypes = method.getGenericParameterTypes(); GenericClass[] ret = new GenericClass[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { Type type = parameterTypes[i]; if (type instanceof Class) { ret[i] = forClass((Class<?>) type); } else if (type instanceof TypeVariable) { String name = ((TypeVariable<?>) type).getName(); Class<?> sub = genericMap.get(declname + "--" + name); if (sub == null) sub = Object.class; ret[i] = forClass(sub); } else { ret[i] = forGenericType(type); } } return ret; }
From source file:org.gradle.model.internal.manage.schema.ModelSchemaExtractor.java
public <T> ModelSchema<T> extract(Class<T> type) throws InvalidManagedModelElementTypeException { validateType(type);//from ww w .j a v a2s . co m List<Method> methodList = Arrays.asList(type.getDeclaredMethods()); if (methodList.isEmpty()) { return new ModelSchema<T>(type, Collections.<ModelProperty<?>>emptyList()); } List<ModelProperty<?>> properties = Lists.newLinkedList(); Map<String, Method> methods = Maps.newHashMap(); for (Method method : methodList) { String name = method.getName(); if (methods.containsKey(name)) { throw invalidMethod(type, name, "overloaded methods are not supported"); } methods.put(name, method); } List<String> methodNames = Lists.newLinkedList(methods.keySet()); List<String> handled = Lists.newArrayList(); for (ListIterator<String> iterator = methodNames.listIterator(); iterator.hasNext();) { String methodName = iterator.next(); Method method = methods.get(methodName); if (methodName.startsWith("get") && !methodName.equals("get")) { if (method.getParameterTypes().length != 0) { throw invalidMethod(type, methodName, "getter methods cannot take parameters"); } Class<?> returnType = method.getReturnType(); if (!returnType.equals(String.class)) { throw invalidMethod(type, methodName, "only String properties are supported"); } // hardcoded for now ModelType<String> propertyType = ModelType.of(String.class); Character getterPropertyNameFirstChar = methodName.charAt(3); if (!Character.isUpperCase(getterPropertyNameFirstChar)) { throw invalidMethod(type, methodName, "the 4th character of the getter method name must be an uppercase character"); } String propertyNameCapitalized = methodName.substring(3); String propertyName = StringUtils.uncapitalize(propertyNameCapitalized); String setterName = "set" + propertyNameCapitalized; if (!methods.containsKey(setterName)) { throw invalidMethod(type, methodName, "no corresponding setter for getter"); } Method setter = methods.get(setterName); handled.add(setterName); if (!setter.getReturnType().equals(void.class)) { throw invalidMethod(type, setterName, "setter method must have void return type"); } Type[] setterParameterTypes = setter.getGenericParameterTypes(); if (setterParameterTypes.length != 1) { throw invalidMethod(type, setterName, "setter method must have exactly one parameter"); } ModelType<?> setterType = ModelType.of(setterParameterTypes[0]); if (!setterType.equals(propertyType)) { throw invalidMethod(type, setterName, "setter method param must be of exactly the same type as the getter returns (expected: " + propertyType + ", found: " + setterType + ")"); } properties.add(new ModelProperty<String>(propertyName, propertyType)); iterator.remove(); } } methodNames.removeAll(handled); // TODO - should call out valid getters without setters if (!methodNames.isEmpty()) { throw invalid(type, "only paired getter/setter methods are supported (invalid methods: [" + Joiner.on(", ").join(methodNames) + "])"); } return new ModelSchema<T>(type, properties); }
From source file:org.openmrs.module.webservices.rest.web.ConversionUtilTest.java
/** * @verifies throw IllegalArgumentException when instance class is null * @see ConversionUtil#getTypeVariableClass(Class, java.lang.reflect.TypeVariable) *///from w w w . jav a2 s. com @Test(expected = IllegalArgumentException.class) public void getTypeVariableClass_shouldThrowIllegalArgumentExceptionWhenInstanceClassIsNull() throws Exception { GrandchildGenericType_Int i = new GrandchildGenericType_Int(); Method setter = PropertyUtils.getPropertyDescriptor(i, "value").getWriteMethod(); Type type = ConversionUtil.getTypeVariableClass(null, (TypeVariable<?>) setter.getGenericParameterTypes()[0]); }
From source file:org.openmrs.module.webservices.rest.web.ConversionUtilTest.java
/** * @verifies return null when actual type cannot be found * @see ConversionUtil#getTypeVariableClass(Class, java.lang.reflect.TypeVariable) *///w w w.java 2 s . c o m @Test public void getTypeVariableClass_shouldReturnNullWhenActualTypeCannotBeFound() throws Exception { GrandchildGenericType_Int i = new GrandchildGenericType_Int(); Method setter = PropertyUtils.getPropertyDescriptor(i, "value").getWriteMethod(); Type type = ConversionUtil.getTypeVariableClass(Temp.class, (TypeVariable<?>) setter.getGenericParameterTypes()[0]); Assert.assertNull(type); }
From source file:GenericClass.java
/** * Search for all occurrencies of a specific method. * <p>// w w w . ja v a 2 s . c om * The type parameters passed in may be Class or null. If they are null, that * means that we don't know which class they should be, if they are a class, * that means we are searching for that class, and the comparison is made on * dereferenced generics. * </p> * <p> * Specifying no parameter types explicitly means "a method without * parameters". * </p> * * @param name * The name of the method * @param parameterTypes * The types of the parameters * @return A list of {@link MethodDef}, ordered with methods from current * class first, then method from superclass and so on. */ public List<MethodDef> findMethods(String name, Class<?>... parameterTypes) { List<MethodDef> founds = new ArrayList<MethodDef>(); Class<?> current = myclass; while (current != null) { Method[] methods = current.getDeclaredMethods(); for (Method method : methods) { if (!method.isBridge() && !method.isSynthetic() && method.getName().equals(name)) { Type[] types = method.getGenericParameterTypes(); if (types.length == parameterTypes.length) { GenericClass[] genericClasses = getParameterTypes(method); Class<?>[] classes = toRawClasses(genericClasses); boolean good = true; for (int i = 0; i < types.length; i++) { if (parameterTypes[i] != null) { if (!classes[i].equals(parameterTypes[i])) { good = false; break; } } } if (good) { MethodDef def = new MethodDef(method, genericClasses); if (!founds.contains(def)) founds.add(def); } } } } current = current.getSuperclass(); } return founds; }
From source file:net.zcarioca.zcommons.config.util.ConfigurationUtilities.java
/** * Searches the bean for any methods annotated with @PostConstruct for * immediate invocation./*from ww w . j ava 2 s . com*/ * * @param bean The bean to process */ void invokePostConstruct(Object bean) throws ConfigurationException { Class<?> beanClass = bean.getClass(); do { for (Method method : beanClass.getDeclaredMethods()) { if (method.isAnnotationPresent(PostConstruct.class)) { Type[] types = method.getGenericParameterTypes(); if (types.length == 0) { // cannot be called on method that takes arguments try { method.invoke(bean, (Object[]) null); } catch (Exception exc) { throw new ConfigurationException( String.format("Could not call method %s on the class %s", method.getName(), bean.getClass().getName()), exc); } } } } } while ((beanClass = beanClass.getSuperclass()) != null); }
From source file:com.legstar.config.commons.LegStarConfigCommons.java
/** * For a given configuration key and value locate a corresponding * setter method and use it./* w w w .j a va2 s . co m*/ * * @param o the bean to set * @param key the configuration key * @param value the configuration value * @throws LegStarConfigurationException if setting value on bean fails */ protected void setValue(final Object o, final String key, final String value) throws LegStarConfigurationException { String setterName = getSetterName(key); if (_log.isDebugEnabled()) { _log.debug("Using setter method: " + setterName + ", for value: " + value); } try { Method[] allMethods = o.getClass().getMethods(); for (Method method : allMethods) { if (method.getName().equals(setterName)) { method.setAccessible(true); Class<?> parm = (Class<?>) method.getGenericParameterTypes()[0]; if (parm.isAssignableFrom(String.class)) { method.invoke(o, value); break; } if (parm.isAssignableFrom(boolean.class)) { method.invoke(o, Boolean.parseBoolean(value)); break; } if (parm.isAssignableFrom(int.class)) { method.invoke(o, Integer.parseInt(value)); break; } if (parm.isAssignableFrom(long.class)) { method.invoke(o, Long.parseLong(value)); break; } if (parm.isAssignableFrom(HostEndpoint.AccessStrategy.class)) { method.invoke(o, AccessStrategy.valueOf(value)); break; } _log.warn("Setter method: " + setterName + ", parameter type: " + parm + ", not compatible with value: " + value); } } } catch (SecurityException e) { throw new LegStarConfigurationException(e); } catch (IllegalArgumentException e) { throw new LegStarConfigurationException(e); } catch (IllegalAccessException e) { throw new LegStarConfigurationException(e); } catch (InvocationTargetException e) { throw new LegStarConfigurationException(e); } }
From source file:org.broadinstitute.gatk.queue.extensions.gatk.GATKExtensionsGenerator.java
/** * Writes the dependents to a scala wrapper that will compile and get picked up by BCEL. * BCEL was missing some classes, such as Enums, when they were defined in the other generated classes. * This generated wrapper makes sure they are explicitly seen by BCEL. * @param dependents Explicit dependencies that need to be packaged. * @throws IOException If the file cannot be written. */// ww w . ja v a 2s . c o m private void writeDependencies(SortedSet<Class<?>> dependents) throws IOException { // Include the enclosing classes too. Scala will be looking for them. SortedSet<Class<?>> enclosings = new TreeSet<Class<?>>(classComparator); for (Class<?> dependent : dependents) for (Class<?> enclosing = dependent; enclosing != null; enclosing = enclosing.getEnclosingClass()) enclosings.add(enclosing); dependents = enclosings; // Oh, and include the classes defined on methods too! enclosings = new TreeSet<Class<?>>(classComparator); for (Class<?> dependent : dependents) { for (Method method : dependent.getDeclaredMethods()) { JVMUtils.addGenericTypes(enclosings, method.getGenericReturnType()); for (Type parameterType : method.getGenericParameterTypes()) JVMUtils.addGenericTypes(enclosings, parameterType); for (Type exceptionType : method.getGenericExceptionTypes()) JVMUtils.addGenericTypes(enclosings, exceptionType); } } dependents = enclosings; // Generate the dependents. String className = "GATKClassDependencies"; StringBuilder classes = new StringBuilder(); for (Class<?> dependent : dependents) { if (dependent.isArray()) continue; if (ArgumentField.isBuiltIn(dependent)) continue; if (!Modifier.isPublic(dependent.getModifiers())) continue; if (classes.length() > 0) classes.append(",").append(NEWLINE); String typeParams = getScalaTypeParams(dependent); classes.append("classOf[").append(dependent.getName().replace("$", ".")).append(typeParams).append("]"); } String content = String.format(GATK_DEPENDENCIES_TEMPLATE, GATK_EXTENSIONS_PACKAGE_NAME, className, classes); writeFile(GATK_EXTENSIONS_PACKAGE_NAME + "." + className, content); }
From source file:org.openmrs.module.webservices.rest.web.ConversionUtilTest.java
/** * @verifies return the actual type if defined on the grand-parent class * @see ConversionUtil#getTypeVariableClass(Class, java.lang.reflect.TypeVariable) *///from w ww .j a va2 s. co m @Test public void getTypeVariableClass_shouldReturnTheActualTypeIfDefinedOnTheGrandparentClass() throws Exception { GrandchildGenericType_Int i = new GrandchildGenericType_Int(); GreatGrandchildGenericType_Int i2 = new GreatGrandchildGenericType_Int(); Method setter = PropertyUtils.getPropertyDescriptor(i, "value").getWriteMethod(); Type type = ConversionUtil.getTypeVariableClass(GrandchildGenericType_Int.class, (TypeVariable<?>) setter.getGenericParameterTypes()[0]); Assert.assertNotNull(type); Assert.assertEquals(Integer.class, type); setter = PropertyUtils.getPropertyDescriptor(i2, "value").getWriteMethod(); type = ConversionUtil.getTypeVariableClass(GreatGrandchildGenericType_Int.class, (TypeVariable<?>) setter.getGenericParameterTypes()[0]); Assert.assertNotNull(type); Assert.assertEquals(Integer.class, type); }