List of usage examples for java.lang.reflect Method getReturnType
public Class<?> getReturnType()
From source file:com.agileapes.couteau.context.spring.event.impl.GenericTranslationScheme.java
@Override public void fillIn(Event originalEvent, ApplicationEvent translated) throws EventTranslationException { if (!(translated instanceof GenericApplicationEvent)) { return;/* w w w.j a v a 2s. c o m*/ } GenericApplicationEvent applicationEvent = (GenericApplicationEvent) translated; final Enumeration<?> propertyNames = applicationEvent.getPropertyNames(); while (propertyNames.hasMoreElements()) { final String property = (String) propertyNames.nextElement(); final Object value = applicationEvent.getProperty(property); final Method method = ReflectionUtils.findMethod(originalEvent.getClass(), "set" + StringUtils.capitalize(property)); if (method == null || !Modifier.isPublic(method.getModifiers()) || method.getParameterTypes().length != 1 || !method.getReturnType().equals(void.class) || !method.getParameterTypes()[0].isInstance(value)) { continue; } try { method.invoke(originalEvent, value); } catch (Exception e) { throw new EventTranslationException("Failed to call setter on original event", e); } } }
From source file:com.invariantproperties.sandbox.springentitylistener.listener.HibernateEntityListenersAdapter.java
public void findMethodsForListener(Object listener) { Class<?> c = listener.getClass(); for (Method m : c.getMethods()) { if (Void.TYPE.equals(m.getReturnType())) { Class<?>[] types = m.getParameterTypes(); if (types.length == 1) { // check for all annotations now... if (m.getAnnotation(PrePersist.class) != null) { if (!preInsert.containsKey(types[0])) { preInsert.put(types[0], new LinkedHashMap<Method, Object>()); }/*w w w . j a v a 2 s . c om*/ preInsert.get(types[0]).put(m, listener); } if (m.getAnnotation(PostPersist.class) != null) { if (!postInsert.containsKey(types[0])) { postInsert.put(types[0], new LinkedHashMap<Method, Object>()); } postInsert.get(types[0]).put(m, listener); } if (m.getAnnotation(PreUpdate.class) != null) { if (!preUpdate.containsKey(types[0])) { preUpdate.put(types[0], new LinkedHashMap<Method, Object>()); } preUpdate.get(types[0]).put(m, listener); } if (m.getAnnotation(PostUpdate.class) != null) { if (!postUpdate.containsKey(types[0])) { postUpdate.put(types[0], new LinkedHashMap<Method, Object>()); } postUpdate.get(types[0]).put(m, listener); } if (m.getAnnotation(PreRemove.class) != null) { if (!preRemove.containsKey(types[0])) { preRemove.put(types[0], new LinkedHashMap<Method, Object>()); } preRemove.get(types[0]).put(m, listener); } if (m.getAnnotation(PostRemove.class) != null) { if (!postRemove.containsKey(types[0])) { postRemove.put(types[0], new LinkedHashMap<Method, Object>()); } postRemove.get(types[0]).put(m, listener); } if (m.getAnnotation(PostLoad.class) != null) { if (!postLoad.containsKey(types[0])) { postLoad.put(types[0], new LinkedHashMap<Method, Object>()); } postLoad.get(types[0]).put(m, listener); } } } } }
From source file:org.ovirt.engine.sdk.common.CollectionDecorator.java
/** * Fetches collection of items from server response * //from w w w . j a v a2 s . c om * @param collection * of public entities * * @return List<R> where Z is a decorator type */ @SuppressWarnings("unchecked") private List<R> fetchCollection(Q collection) { for (Method m : collection.getClass().getMethods()) { // TODO: make sure this is a right getter method if (m.getName().startsWith("get") && m.getReturnType().equals(List.class)) { try { return (List<R>) m.invoke(collection); } catch (Exception e) { e.printStackTrace(); // TODO: log exception } } } return null; }
From source file:com.michelin.cio.hudson.plugins.maskpasswords.MaskPasswordsConfig.java
/** * Returns true if the specified parameter value class name corresponds to * a parameter definition class name selected in Hudson's/Jenkins' main * configuration screen./*w w w . ja v a2s .c o m*/ */ public boolean isMasked(String paramValueClassName) { try { // do we need to build the set of parameter values which must be // masked? if (maskPasswordsParamValueClasses == null) { maskPasswordsParamValueClasses = new LinkedHashSet<String>(); // The only way to find parameter definition/parameter value // couples is to reflect the 3 methods of parameter definition // classes which instantiate the parameter value. // This means that this algorithm expects that the developers do // clearly redefine the return type when implementing parameter // definitions/values. for (String paramDefClassName : maskPasswordsParamDefClasses) { final Class paramDefClass = Hudson.getInstance().getPluginManager().uberClassLoader .loadClass(paramDefClassName); List<Method> methods = new ArrayList<Method>() { { // ParameterDefinition.getDefaultParameterValue() try { add(paramDefClass.getMethod("getDefaultParameterValue")); } catch (Exception e) { LOGGER.log(Level.INFO, "No getDefaultParameterValue(String) method for " + paramDefClass); } // ParameterDefinition.createValue(String) try { add(paramDefClass.getMethod("createValue", String.class)); } catch (Exception e) { LOGGER.log(Level.INFO, "No createValue(String) method for " + paramDefClass); } // ParameterDefinition.createValue(org.kohsuke.stapler.StaplerRequest, net.sf.json.JSONObjec) try { add(paramDefClass.getMethod("createValue", StaplerRequest.class, JSONObject.class)); } catch (Exception e) { LOGGER.log(Level.INFO, "No createValue(StaplerRequest, JSONObject) method for " + paramDefClass); } } }; for (Method m : methods) { maskPasswordsParamValueClasses.add(m.getReturnType().getName()); } } } } catch (Exception e) { LOGGER.log(Level.WARNING, "Error while initializing Mask Passwords: " + e); return false; } return maskPasswordsParamValueClasses.contains(paramValueClassName); }
From source file:cn.com.sinosoft.util.exception.ExceptionUtils.java
/** * <p>//from w w w . ja va2s . co m * Checks whether this <code>Throwable</code> class can store a cause. * </p> * * <p> * This method does <b>not</b> check whether it actually does store a cause. * <p> * * @param throwable * the <code>Throwable</code> to examine, may be null * @return boolean <code>true</code> if nested otherwise <code>false</code> * @since 2.0 */ public static boolean isNestedThrowable(Throwable throwable) { if (throwable == null) { return false; } if (throwable instanceof Nestable) { return true; } else if (throwable instanceof SQLException) { return true; } else if (throwable instanceof InvocationTargetException) { return true; } else if (isThrowableNested()) { return true; } Class cls = throwable.getClass(); synchronized (CAUSE_METHOD_NAMES_LOCK) { for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) { try { Class<?>[] parameterTypes = {}; Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], parameterTypes); if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { return true; } } catch (NoSuchMethodException ignored) { // exception ignored } catch (SecurityException ignored) { // exception ignored } } } try { Field field = cls.getField("detail"); if (field != null) { return true; } } catch (NoSuchFieldException ignored) { // exception ignored } catch (SecurityException ignored) { // exception ignored } return false; }
From source file:com.geemvc.view.DefaultStreamViewHandler.java
@Override public void handle(Result result, RequestContext requestCtx) throws ServletException, IOException { HttpServletResponse response = (HttpServletResponse) requestCtx.getResponse(); if (result.length() > 0) { response.setContentLength((int) result.length()); }//from www .j a va 2 s .c o m if (result.filename() != null) { if (result.attachment()) { response.setHeader("Content-disposition", "attachment; filename=" + result.filename()); } else { response.setHeader("Content-disposition", "filename=" + result.filename()); } } if (result.contentType() != null) { response.setContentType(result.contentType()); } if (result.rangeSupport()) { // TODO: range-support } if (result.result() != null) { RequestHandler requestHandler = requestCtx.requestHandler(); Method handlerMethod = requestHandler.handlerMethod(); if (configuration.isJaxRsEnabled()) { MessageBodyWriter mbw = injector.getInstance(Providers.class).getMessageBodyWriter( handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType())); if (mbw != null && mbw.isWriteable(handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()))) { MultivaluedMap<String, Object> httpResponseHeaders = injector.getInstance(MultivaluedMap.class); mbw.writeTo(result.result(), handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()), httpResponseHeaders, response.getOutputStream()); } else { response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } } else { log.info( "Unable to convert the result object of type '{}' to the media type '{}' as the JAX-RS runtime has been disabled.", () -> result.result().getClass().getName(), () -> response.getContentType()); response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); } return; } if (result.stream() != null) { IOUtils.copy(result.stream(), response.getOutputStream()); } else if (result.reader() != null) { IOUtils.copy(result.reader(), response.getOutputStream(), result.characterEncoding()); } else if (result.output() != null) { response.getOutputStream().write(result.output().getBytes()); } else { throw new IllegalStateException( "You must provide either a stream, a reader or a string output when using Results.stream(). "); } }
From source file:gool.generator.xml.XmlCodePrinter.java
/** * Translate GOOL node to XML Element.//from w w w . j a va2 s . co m * * @param node * GOOL node * @param document * XML Document * @return XML Element */ private Element NodeToElement(Object node, Document document) { // element create for return Element newElement = null; // check if the parameter does not cause trouble if (node == null || node.getClass().getName().equals("gool.generator.xml.XmlPlatform")) return null; if (node.getClass().isAssignableFrom(gool.ast.core.Node.class)) { return null; } if (node.getClass().getName().equals("gool.ast.core.ClassDef")) { if (classdefok) classdefok = false; else return null; } // Create the new Element newElement = document.createElement(node.getClass().getName().substring(9)); // find every method to find every child node Method[] meths = node.getClass().getMethods(); for (Method meth : meths) { Class<?> laCl = meth.getReturnType(); // check if the method return type is a node. if (gool.ast.core.Node.class.isAssignableFrom(laCl) && (meth.getParameterTypes().length == 0) /* && nbNode<1000 */) { // Debug for recursion // nbNode++; // Log.d(laCl.getName() + "\n" + nbNode); try { gool.ast.core.Node newNode = (gool.ast.core.Node) meth.invoke(node); // detect recursion risk. boolean recursionRisk = (newNode == node) ? true : false; if (methexclude.containsKey(node.getClass().getName())) { for (String exmeth : methexclude.get(node.getClass().getName())) { if (newNode == null || meth.getName().equals(exmeth)) recursionRisk = true; } } if (recursionRisk) { Element newElement2 = document.createElement(node.getClass().getName().substring(9)); newElement2.setTextContent("recursion risk detected!"); newElement.appendChild(newElement2); } else { Element el = NodeToElement(newNode, document); if (el != null) { el.setAttribute("getterName", meth.getName()); newElement.appendChild(el); } } } catch (Exception e) { Log.e(e); System.exit(1); } } // if the method return node list. else if (java.util.List.class.isAssignableFrom(laCl)) { try { java.util.List<Object> listObj = (java.util.List<Object>) meth.invoke(node); for (Object o : listObj) { Element el = NodeToElement(o, document); if (el != null) { el.setAttribute("getterName", meth.getName()); newElement.appendChild(el); } } } catch (Exception e) { Log.e(e); System.exit(1); } } // generate XML attribute for getter else if (meth.getName().startsWith("get") && !meth.getName().equals("getCode") && (meth.getParameterTypes().length == 0)) { try { if (!attrexclude.contains(meth.getName())) newElement.setAttribute(meth.getName().substring(3), meth.invoke(node) == null ? "null" : meth.invoke(node).toString()); } catch (Exception e) { Log.e(e); System.exit(1); } } // generate XML attribute for iser else if (meth.getName().startsWith("is") && (meth.getParameterTypes().length == 0)) { try { if (!attrexclude.contains(meth.getName())) newElement.setAttribute(meth.getName().substring(2), meth.invoke(node) == null ? "null" : meth.invoke(node).toString()); } catch (Exception e) { Log.e(e); System.exit(1); } } } return newElement; }
From source file:com.mastercard.test.spring.security.WatchWithUserTestExecutionListener.java
/** * Locate repeated annoations within a Java 8 annotation container. If the annotation * provided is a container for annotations with the @Repeatable annotation, then the contained * annotations are returned.//from w w w . j a va 2 s . com * @param annotation The annotation to investigate for repeated annotations. * @return A list containing repeated annotations if present. */ private List<Annotation> findRepeatableAnnotations(Annotation annotation) { List<Annotation> retVal = new ArrayList<>(); for (Method method : annotation.annotationType().getMethods()) { if (method.getName().equals("value")) { if (method.getReturnType().isArray()) { try { Annotation[] types = (Annotation[]) method.invoke(annotation); retVal.addAll(Arrays.asList(types)); } catch (IllegalAccessException | InvocationTargetException | ClassCastException e) { //ignore, must not be a container for annotations } } break; } } return retVal; }
From source file:io.fabric8.spring.boot.AbstractServiceRegistar.java
@Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { for (Method method : REFLECTIONS.getMethodsAnnotatedWith(Factory.class)) { String methodName = method.getName(); Class sourceType = getSourceType(method); Class targetType = method.getReturnType(); Class beanType = method.getDeclaringClass(); BeanDefinitionHolder holder = createConverterBean(beanType, methodName, sourceType, targetType); BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry); }//from w w w .ja v a 2 s .co m for (Field field : REFLECTIONS.getFieldsAnnotatedWith(ServiceName.class)) { Class targetClass = field.getType(); Alias alias = field.getAnnotation(Alias.class); ServiceName name = field.getAnnotation(ServiceName.class); PortName port = field.getAnnotation(PortName.class); Protocol protocol = field.getAnnotation(Protocol.class); External external = field.getAnnotation(External.class); String serviceName = name != null ? name.value() : null; //We copy the service since we are going to add properties to it. Service serviceInstance = new ServiceBuilder(getService(serviceName)).build(); String servicePort = port != null ? port.value() : null; String serviceProtocol = protocol != null ? protocol.value() : DEFAULT_PROTOCOL; Boolean serviceExternal = external != null && external.value(); String serviceAlias = alias != null ? alias.value() : createAlias(serviceName, targetClass, serviceProtocol, servicePort, serviceExternal); //Add annotation info as additional properties serviceInstance.getAdditionalProperties().put(ALIAS, serviceAlias); serviceInstance.getAdditionalProperties().put(PROTOCOL, serviceProtocol); serviceInstance.getAdditionalProperties().put(EXTERNAL, serviceExternal); //We don't want to add a fallback value to the attributes. if (port != null) { serviceInstance.getAdditionalProperties().put(PORT, servicePort); } BeanDefinitionHolder holder = createServiceDefinition(serviceInstance, serviceAlias, serviceProtocol, servicePort, targetClass); BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry); } }
From source file:com.jsen.javascript.java.HostedJavaMethod.java
@Override public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { InvocableMember<?> nearestInvocable = getNearestObjectFunction(args, objectFunctions); if (nearestInvocable == null) { throw new FunctionException("Unable to match nearest function"); }/*from ww w . jav a 2s . c o m*/ FunctionMember nearestFunctionObject = (FunctionMember) nearestInvocable; Method functionMethod = nearestFunctionObject.getMember(); Class<?> returnType = functionMethod.getReturnType(); Class<?> expectedTypes[] = functionMethod.getParameterTypes(); Object[] castedArgs = castArgs(expectedTypes, args); try { Object returned = functionMethod.invoke(object, castedArgs); return (returnType == Void.class) ? Undefined.instance : returned; } catch (Exception e) { throw new UnknownException("Unable to invoke function " + nearestFunctionObject.getName(), e); } }