List of usage examples for java.lang.reflect Method getReturnType
public Class<?> getReturnType()
From source file:ca.uhn.fhir.rest.method.BaseResourceReturningMethodBinding.java
@SuppressWarnings("unchecked") public BaseResourceReturningMethodBinding(Class<?> theReturnResourceType, Method theMethod, FhirContext theContext, Object theProvider) { super(theMethod, theContext, theProvider); Class<?> methodReturnType = theMethod.getReturnType(); if (Collection.class.isAssignableFrom(methodReturnType)) { myMethodReturnType = MethodReturnTypeEnum.LIST_OF_RESOURCES; Class<?> collectionType = ReflectionUtil.getGenericCollectionTypeOfMethodReturnType(theMethod); if (collectionType != null) { if (!Object.class.equals(collectionType) && !IBaseResource.class.isAssignableFrom(collectionType)) { throw new ConfigurationException( "Method " + theMethod.getDeclaringClass().getSimpleName() + "#" + theMethod.getName() + " returns an invalid collection generic type: " + collectionType); }/*from w w w . j a v a 2 s .c om*/ } myResourceListCollectionType = collectionType; } else if (IBaseResource.class.isAssignableFrom(methodReturnType)) { if (Modifier.isAbstract(methodReturnType.getModifiers()) == false && theContext .getResourceDefinition((Class<? extends IBaseResource>) methodReturnType).isBundle()) { myMethodReturnType = MethodReturnTypeEnum.BUNDLE_RESOURCE; } else { myMethodReturnType = MethodReturnTypeEnum.RESOURCE; } } else if (Bundle.class.isAssignableFrom(methodReturnType)) { myMethodReturnType = MethodReturnTypeEnum.BUNDLE; } else if (IBundleProvider.class.isAssignableFrom(methodReturnType)) { myMethodReturnType = MethodReturnTypeEnum.BUNDLE_PROVIDER; } else if (MethodOutcome.class.isAssignableFrom(methodReturnType)) { myMethodReturnType = MethodReturnTypeEnum.METHOD_OUTCOME; } else { throw new ConfigurationException("Invalid return type '" + methodReturnType.getCanonicalName() + "' on method '" + theMethod.getName() + "' on type: " + theMethod.getDeclaringClass().getCanonicalName()); } if (theReturnResourceType != null) { if (IBaseResource.class.isAssignableFrom(theReturnResourceType)) { if (Modifier.isAbstract(theReturnResourceType.getModifiers()) || Modifier.isInterface(theReturnResourceType.getModifiers())) { // If we're returning an abstract type, that's ok } else { myResourceType = (Class<? extends IResource>) theReturnResourceType; myResourceName = theContext.getResourceDefinition(myResourceType).getName(); } } } myPreferTypesList = createPreferTypesList(); }
From source file:com.github.pith.typedconfig.TypedConfigPlugin.java
private Map<Class<Object>, Object> initConfigClasses(Collection<Class<?>> configClasses, Configuration configuration) { Map<Class<Object>, Object> configClassesMap = new HashMap<Class<Object>, Object>(); for (Class<?> configClass : configClasses) { try {/*w ww . ja v a 2 s . c o m*/ Object configObject = configClass.newInstance(); for (Method method : configClass.getDeclaredMethods()) { if (method.getName().startsWith("get")) { Object property = configuration.getProperty(configClass.getSimpleName().toLowerCase() + method.getName().substring(3).toLowerCase()); if (property != null) { try { Method setter = configClass.getDeclaredMethod("set" + method.getName().substring(3), method.getReturnType()); setter.setAccessible(true); setter.invoke(configObject, property); } catch (NoSuchMethodException e) { throw new IllegalStateException("The TypedConfigPlugin can't initialize " + method.getName() + " because there is no associated setter."); } catch (InvocationTargetException e) { if (e.getCause() != null) { throw new IllegalStateException("Failed to initialize " + method.getName(), e.getCause()); } } } } } //noinspection unchecked configClassesMap.put((Class<Object>) configClass, configObject); } catch (InstantiationException e) { throw new IllegalStateException("Failed to instantiate " + configClass, e.getCause()); } catch (IllegalAccessException e) { throw new IllegalStateException("Failed to access the constructor of " + configClass, e.getCause()); } } return configClassesMap; }
From source file:com.msopentech.odatajclient.proxy.api.impl.EntityContainerInvocationHandler.java
@Override @SuppressWarnings("unchecked") public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if (isSelfMethod(method, args)) { return invokeSelfMethod(method, args); } else if ("flush".equals(method.getName()) && ArrayUtils.isEmpty(args)) { new Container(client, factory).flush(); return ClassUtils.returnVoid(); } else {/*w ww . j a v a 2 s .c om*/ final Annotation[] methodAnnots = method.getAnnotations(); // 1. access top-level entity sets if (methodAnnots.length == 0) { final Class<?> returnType = method.getReturnType(); return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { returnType }, EntitySetInvocationHandler.getInstance(returnType, this)); } // 2. invoke function imports else if (methodAnnots[0] instanceof Operation) { final com.msopentech.odatajclient.engine.metadata.edm.v3.EntityContainer container = getFactory() .getMetadata().getSchema(schemaName).getEntityContainer(entityContainerName); final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp = container .getFunctionImport(((Operation) methodAnnots[0]).name()); final URIBuilder uriBuilder = client.getURIBuilder(factory.getServiceRoot()) .appendFunctionImportSegment(URIUtils.rootFunctionImportURISegment(container, funcImp)); return functionImport((Operation) methodAnnots[0], method, args, uriBuilder.build(), funcImp); } else { throw new UnsupportedOperationException("Method not found: " + method); } } }
From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java
protected boolean isMap(Method method) { final Class<?> type = method.getReturnType(); return Map.class.isAssignableFrom(type); }
From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java
protected boolean isCollection(Method method) { final Class<?> type = method.getReturnType(); return Collection.class.isAssignableFrom(type); }
From source file:com.joliciel.talismane.machineLearning.features.DynamicSourceCodeBuilderImpl.java
/** * Replace static arguments by their dynamic equivalents. * @param feature/* ww w . ja v a 2 s. c o m*/ */ void dynamise(Feature<T, ?> feature) { try { if (LOG.isDebugEnabled()) LOG.debug("Dynamising feature " + feature.getName()); Method[] methods = feature.getClass().getDeclaredMethods(); Map<String, Method> getMethods = new HashMap<String, Method>(); Map<String, Method> setMethods = new HashMap<String, Method>(); Map<String, Method> getArrayMethods = new HashMap<String, Method>(); for (Method method : methods) { if (method.getName().startsWith("get")) { if (Feature.class.isAssignableFrom(method.getReturnType())) { getMethods.put(method.getName().substring(3), method); } else if (method.getReturnType().isArray() && Feature.class.isAssignableFrom(method.getReturnType().getComponentType())) { getArrayMethods.put(method.getName().substring(3), method); } } else if (method.getName().startsWith("set")) { if (Feature.class.isAssignableFrom(method.getParameterTypes()[0])) { setMethods.put(method.getName().substring(3), method); } } } for (String getMethodKey : getMethods.keySet()) { Method getMethod = getMethods.get(getMethodKey); Method setMethod = setMethods.get(getMethodKey); if (setMethod != null) { if (LOG.isTraceEnabled()) LOG.trace("Dynamising argument: " + getMethod.getName()); @SuppressWarnings("unchecked") Feature<T, ?> argument = (Feature<T, ?>) getMethod.invoke(feature); DynamicSourceCodeBuilder<T> argumentBuilder = this.dynamiser.getBuilder(argument); Feature<T, ?> dynamicArgument = argumentBuilder.getFeature(); setMethod.invoke(feature, dynamicArgument); } } for (String getArrayMethodKey : getArrayMethods.keySet()) { Method getArrayMethod = getArrayMethods.get(getArrayMethodKey); @SuppressWarnings("unchecked") Feature<T, ?>[] argumentArray = (Feature<T, ?>[]) getArrayMethod.invoke(feature); @SuppressWarnings("unchecked") Feature<T, ?>[] dynamisedArgumentArray = new Feature[argumentArray.length]; int i = 0; for (Feature<T, ?> argument : argumentArray) { DynamicSourceCodeBuilder<T> argumentBuilder = this.dynamiser.getBuilder(argument); Feature<T, ?> dynamicArgument = argumentBuilder.getFeature(); dynamisedArgumentArray[i++] = dynamicArgument; } for (i = 0; i < argumentArray.length; i++) { argumentArray[i] = dynamisedArgumentArray[i]; } } } catch (IllegalArgumentException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } catch (IllegalAccessException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } catch (InvocationTargetException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } }
From source file:org.codehaus.griffon.commons.ClassPropertyFetcher.java
private void init() { FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() { public void doWith(Field field) { if (field.isSynthetic()) return; final int modifiers = field.getModifiers(); if (!Modifier.isPublic(modifiers)) return; final String name = field.getName(); if (name.indexOf('$') == -1) { boolean staticField = Modifier.isStatic(modifiers); if (staticField) { staticFetchers.put(name, new FieldReaderFetcher(field, staticField)); } else { instanceFetchers.put(name, new FieldReaderFetcher(field, staticField)); }//from ww w. ja v a2 s . c o m } } }; MethodCallback methodCallback = new ReflectionUtils.MethodCallback() { public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if (method.isSynthetic()) return; if (!Modifier.isPublic(method.getModifiers())) return; if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) { if (method.getParameterTypes().length == 0) { String name = method.getName(); if (name.indexOf('$') == -1) { if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3))) { name = name.substring(3); } else if (name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2)) && (method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class)) { name = name.substring(2); } PropertyFetcher fetcher = new GetterPropertyFetcher(method, true); staticFetchers.put(name, fetcher); staticFetchers.put(StringUtils.uncapitalize(name), fetcher); } } } } }; List<Class<?>> allClasses = resolveAllClasses(clazz); for (Class<?> c : allClasses) { Field[] fields = c.getDeclaredFields(); for (Field field : fields) { try { fieldCallback.doWith(field); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access field '" + field.getName() + "': " + ex); } } Method[] methods = c.getDeclaredMethods(); for (Method method : methods) { try { methodCallback.doWith(method); } catch (IllegalAccessException ex) { throw new IllegalStateException( "Shouldn't be illegal to access method '" + method.getName() + "': " + ex); } } } propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor desc : propertyDescriptors) { Method readMethod = desc.getReadMethod(); if (readMethod != null) { boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers()); if (staticReadMethod) { staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } else { instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod)); } } } }
From source file:org.jboss.seam.spring.utils.AnnotationInvocationHandler.java
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // delegate methods to if (method.getDeclaringClass().equals(AnnotationInvocationHandler.class) || method.getDeclaringClass().equals(Object.class) || method.getDeclaringClass().equals(Annotation.class)) { return method.invoke(this, args); }/*from w w w .ja v a 2s . co m*/ if (registeredValues != null && registeredValues.containsKey(method.getName())) { if (conversionService != null) { return conversionService.convert(registeredValues.get(method.getName()), method.getReturnType()); } else { return registeredValues.get(method.getName()); } } else { return method.getDefaultValue(); } }
From source file:com.mnt.base.web.action.impl.AbstractActionControllerManager.java
protected Object processRequest(ActionController actionController, String[] secondLevelPaths, String requestUri, String method, Map<String, Object> parameters) { if (log.isDebugEnabled()) { log.debug("Request: " + requestUri + ", method: " + method + ", parameters: " + parameters); }// w w w .j a v a2 s . c o m Object responseHolder = null; if (actionController != null) { // check if exists the type first String type = ActionController.getParameter(parameters, ActionController.K_TYPE); MethodInfoHolder mih = null; if (CommonUtil.isEmpty(type)) { boolean defaultFlag = false; String resValue = null; if (secondLevelPaths.length == 2) { resValue = secondLevelPaths[1]; } if (CommonUtil.isEmpty(resValue)) { resValue = ACMethod.DEFAULT_RESOURCE_DEF; defaultFlag = true; } if (true) { List<ResourceInfoHolder> rihs = acResourcesMap.get(actionController); if (rihs != null) { for (ResourceInfoHolder rih : rihs) { // default only match the default if (defaultFlag) { if (rih.isDefault) { mih = rih; break; } else { continue; } } Matcher matcher = rih.pattern.matcher(resValue); if (matcher.matches()) { for (String key : rih.paramsIndexMap.keySet()) { parameters.put(key, matcher.group(rih.paramsIndexMap.get(key))); } mih = rih; break; } } } } } else { Map<String, MethodInfoHolder> mihs = acMethodsMap.get(actionController); if (mihs != null) { mih = mihs.get(type); } } if (mih != null) { ACMethod acMethod = mih.acMethod; if (!acMethod.accessCheck() || accessChecker.accessable(parameters, acMethod.checkLevel(), acMethod.accessRole())) { List<Object> paramVals = new ArrayList<Object>(); Map<String, Class<?>> paramsSpec = mih.paramsMap; if (paramsSpec != null) { for (String key : paramsSpec.keySet()) { if (ACParam.ALL_PARAMS.equals(key)) { paramVals.add(parameters); } else if (ACParam.RESPONSE_MAP.equals(key)) { responseHolder = new LinkedHashMap<String, Object>(); paramVals.add(responseHolder); } else if (key.startsWith(ACParam.NULL_PREFIX)) { paramVals.add(null); } else if (key.startsWith(ACParam.BEAN_PREFIX)) { Object beanObj = createBeanObj(mih.beanFieldDefMap.get(key), paramsSpec.get(key), parameters); paramVals.add(beanObj); } else { paramVals.add( ActionController.getParameterValue(parameters, key, paramsSpec.get(key))); } } } Method mtd = mih.method; try { if (mtd.getReturnType() == Void.class) { mtd.invoke(actionController.getController(), paramVals.toArray()); } else { Object result = mtd.invoke(actionController.getController(), paramVals.toArray()); responseHolder = (responseHolder == null) ? result : responseHolder; } } catch (Exception e) { log.error("Error when process the request by ActionController", e); Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put(ActionController.K_RESULT, ActionController.SYSTEM_INTERNAL_ERROR); responseHolder = resultMap; } finally { paramVals.clear(); } } else { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put(ActionController.K_RESULT, ActionController.ACCESS_NO_PRIVILEGE); responseHolder = resultMap; } } else { try { responseHolder = actionController.handleRequest(method, parameters); } catch (Exception e) { log.error("Error when process the request by ActionController", e); } } } else { log.warn("Invalid second level path access: " + "Request: " + requestUri + ", method: " + method + ", parameters: " + parameters); } return responseHolder; }
From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java
/** * <p>Reads class' metadata and returns a {@link XmlEventsPattern pattern of XML events} which may be used to marshal * an object of the analyzed class.<?p> * //from ww w. j a va 2 s . co m * @return */ public TypedPattern<T> analyze() { TypedPattern<T> result = this.patternRegistry.findPatternByClass(this.clazz); if (result != null) return result; log.trace("Analyzing {} class with {} type name", this.clazz.getName(), this.typeName); // analyze fields ReflectionUtils.doWithFields(this.clazz, this, new FieldFilter() { @Override public boolean matches(Field field) { return !Modifier.isStatic(field.getModifiers()); } }); // analyze get/set methods - even private ones! ReflectionUtils.doWithMethods(this.clazz, this, new MethodFilter() { @Override public boolean matches(Method method) { boolean match = true; // is it getter? match &= method.getName().startsWith("get"); match &= method.getParameterTypes().length == 0; match &= method.getReturnType() != Void.class; // is there a setter? if (match) { Method setter = ReflectionUtils.findMethod(clazz, method.getName().replaceFirst("^get", "set"), method.getReturnType()); // TODO: maybe allow non-void returning setters as Spring-Framework already does? Now: yes match = setter != null || Collection.class.isAssignableFrom(method.getReturnType()); } return match; } }); if (this.valueMetadata != null && this.childElementMetadata.size() == 0 && this.childAttributeMetadata.size() == 0) { // we have a special case, where Java class becomes simpleType: // - formatting the analyzed class is really formatting the value // - the type information of the analyzed class is not changed! log.trace("Changing {} class' pattern to SimpleContentPattern", this.clazz.getName()); SimpleContentPattern<T> valuePattern = SimpleContentPattern.newValuePattern(this.typeName, this.clazz); SimpleContentPattern<?> simpleTypePattern = (SimpleContentPattern<?>) this.valueMetadata.getPattern(); valuePattern.setFormatter( PeelingFormatter.newPeelingFormatter(this.valueMetadata, simpleTypePattern.getFormatter())); result = valuePattern; } else { if (this.valueMetadata != null && this.childElementMetadata.size() > 0) { throw new RuntimeException("TODO: can't mix @XmlValue and @XmlElements"); } // we have complex type (possibly with simpleContent, when there's @XmlValue + one or more @XmlAttributes) // @XmlAttributes first. then @XmlElements this.childAttributeMetadata.addAll(this.childElementMetadata); if (this.valueMetadata != null) this.childAttributeMetadata.add(this.valueMetadata); result = ComplexTypePattern.newContentModelPattern(this.typeName, this.clazz, this.childAttributeMetadata); } if (log.isTraceEnabled()) log.trace("-> Class {} was mapped to {} with {} XSD type", this.clazz.getName(), result, this.typeName); return result; }