List of usage examples for java.lang.reflect Method getReturnType
public Class<?> getReturnType()
From source file:com.espertech.esper.epl.db.DatabaseDSFactoryConnFactory.java
/** * Ctor.//from w w w . j a v a2 s .c om * @param dsConfig is the datasource object name and initial context properties. * @param connectionSettings are the connection-level settings * @throws DatabaseConfigException when the factory cannot be configured */ public DatabaseDSFactoryConnFactory(ConfigurationDBRef.DataSourceFactory dsConfig, ConfigurationDBRef.ConnectionSettings connectionSettings) throws DatabaseConfigException { this.connectionSettings = connectionSettings; Class clazz; try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); clazz = Class.forName(dsConfig.getFactoryClassname(), true, cl); } catch (ClassNotFoundException e) { throw new DatabaseConfigException("Class '" + dsConfig.getFactoryClassname() + "' cannot be loaded"); } Object obj; try { obj = clazz.newInstance(); } catch (InstantiationException e) { throw new ConfigurationException("Class '" + clazz + "' cannot be instantiated"); } catch (IllegalAccessException e) { throw new ConfigurationException("Illegal access instantiating class '" + clazz + "'"); } // find method : static DataSource createDataSource(Properties properties) Method method; try { method = clazz.getMethod("createDataSource", Properties.class); } catch (NoSuchMethodException e) { throw new ConfigurationException("Class '" + clazz + "' does not provide a static method by name createDataSource accepting a single Properties object as parameter"); } if (method == null) { throw new ConfigurationException("Class '" + clazz + "' does not provide a static method by name createDataSource accepting a single Properties object as parameter"); } if (method.getReturnType() != DataSource.class) { throw new ConfigurationException("On class '" + clazz + "' the static method by name createDataSource does not return a DataSource"); } Object result; try { result = method.invoke(obj, dsConfig.getProperties()); } catch (IllegalAccessException e) { throw new ConfigurationException( "Class '" + clazz + "' failed in method createDataSource :" + e.getMessage(), e); } catch (InvocationTargetException e) { throw new ConfigurationException( "Class '" + clazz + "' failed in method createDataSource :" + e.getMessage(), e); } if (result == null) { throw new ConfigurationException("Method createDataSource returned a null value for DataSource"); } dataSource = (DataSource) result; }
From source file:com.vmware.photon.controller.swagger.resources.SwaggerJsonListing.java
/** * Looks at a method's annotations (return type, parameters, path, etc.) and adds them to the API representations. * If a return type is a subresource this method will recurse back to getApiListings to have it parsed. * * @param models The hashmap of models that are being documented so that they can be referenced by swagger-ui. * @param method The method to document. * @param uriBuilder A uribuilder that helps this resource determine its true http path. * @param parentParams The parameters of parent resources, so that they can be documented by subresources. * @return A list of SwaggerApiListing.//w ww .j a va2s. c om */ private List<SwaggerApiListing> getMethodData(HashMap<String, SwaggerModel> models, ResourceMethod method, UriBuilder uriBuilder, List<SwaggerParameter> parentParams, Map<Resource, Class<?>> resourcesMap) { Method definitionMethod = method.getInvocable().getDefinitionMethod(); Class<?> returnType = definitionMethod.getReturnType(); boolean returnTypeIsSubResource = false; Resource returnResource = null; // If the return type isn't primitive, it could be a subresource type. if (!PRIMITIVE_TYPES.contains(returnType.getSimpleName())) { returnResource = Resource.from(returnType); returnTypeIsSubResource = returnResource != null && resourcesMap.containsKey(returnResource) && resourcesMap.get(returnResource).isAnnotationPresent(Api.class); } Path methodPath = definitionMethod.getAnnotation(Path.class); if (methodPath != null) { uriBuilder.path(methodPath.value()); } if (returnTypeIsSubResource) { // If the return type is a subresource, recurse back to getApiListings. return getApiListings(models, returnResource, uriBuilder.clone(), getOperation(models, method, parentParams).getParameters(), resourcesMap); } else { // Generate the docs for this endpoint. SwaggerOperation operation = getOperation(models, method, parentParams); addModel(models, returnType); List<SwaggerOperation> operations = new ArrayList<>(); operations.add(operation); SwaggerApiListing listing = new SwaggerApiListing(); listing.setPath(uriBuilder.toTemplate()); listing.setOperations(operations); List<SwaggerApiListing> apiListings = new ArrayList<>(); apiListings.add(listing); return apiListings; } }
From source file:org.LexGrid.LexBIG.caCore.client.proxy.DataServiceProxyHelperImpl.java
/** * Account for all the extra methods Castor puts in its beans. This needs to be done because * the properties themselves may not be initialized by Hibernate (lazy loaded), but calling * one of these methods on a Castor bean will try to invoke the un-initialized property. So, * we have to determine what method is being called and process the result accordingly. * //from ww w . j a v a2 s . c o m * @param result The right result given the Method being called. * @param methodInvocation The method being invoked. * @return */ protected Object accountForCastorMethods(List result, MethodInvocation methodInvocation) { Method method = methodInvocation.getMethod(); String methodName = method.getName(); if (methodName.startsWith("get") && methodName.endsWith("Count")) { return new Integer(result.size()); } if (methodName.startsWith("enumerate")) { return java.util.Collections.enumeration(result); } if (methodName.startsWith("iterate")) { return result.iterator(); } if (methodName.startsWith("get") && method.getReturnType().isArray()) { Class returnType = method.getReturnType().getComponentType(); Object[] array = (Object[]) Array.newInstance(returnType, result.size()); return result.toArray(array); } if (methodName.startsWith("get") && method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == int.class) { return result.get((Integer) methodInvocation.getArguments()[0]); } return result; }
From source file:hudson.model.Descriptor.java
/** * Infers the type of the corresponding {@link Describable} from the outer class. * This version works when you follow the common convention, where a descriptor * is written as the static nested class of the describable class. * /*from w w w .j a va2s . c o m*/ * @since 1.278 */ protected Descriptor() { this.clazz = (Class<T>) getClass().getEnclosingClass(); if (clazz == null) throw new AssertionError(getClass() + " doesn't have an outer class. Use the constructor that takes the Class object explicitly."); // detect an type error Type bt = Types.getBaseClass(getClass(), Descriptor.class); if (bt instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) bt; // this 't' is the closest approximation of T of Descriptor<T>. Class t = Types.erasure(pt.getActualTypeArguments()[0]); if (!t.isAssignableFrom(clazz)) throw new AssertionError("Outer class " + clazz + " of " + getClass() + " is not assignable to " + t + ". Perhaps wrong outer class?"); } // detect a type error. this Descriptor is supposed to be returned from getDescriptor(), so make sure its type match up. // this prevents a bug like http://www.nabble.com/Creating-a-new-parameter-Type-%3A-Masked-Parameter-td24786554.html try { Method getd = clazz.getMethod("getDescriptor"); if (!getd.getReturnType().isAssignableFrom(getClass())) { throw new AssertionError(getClass() + " must be assignable to " + getd.getReturnType()); } } catch (NoSuchMethodException e) { throw new AssertionError(getClass() + " is missing getDescriptor method."); } }
From source file:com.haulmont.chile.core.loader.ChileAnnotationsLoader.java
@SuppressWarnings({ "unchecked" }) protected MetadataObjectInfo<Range> loadRange(MetaProperty metaProperty, Class type, Map<String, Object> map) { Datatype datatype = (Datatype) map.get("datatype"); if (datatype != null) { return new MetadataObjectInfo<>(new DatatypeRange(datatype)); }//from ww w . ja v a 2 s .c om datatype = Datatypes.get(type); if (datatype != null) { MetaClass metaClass = metaProperty.getDomain(); Class javaClass = metaClass.getJavaClass(); try { String name = "get" + StringUtils.capitalize(metaProperty.getName()); Method method = javaClass.getMethod(name); Class<Enum> returnType = (Class<Enum>) method.getReturnType(); if (returnType.isEnum()) { return new MetadataObjectInfo<>(new EnumerationRange(new EnumerationImpl<>(returnType))); } } catch (NoSuchMethodException e) { // ignore } return new MetadataObjectInfo<>(new DatatypeRange(datatype)); } else if (type.isEnum()) { return new MetadataObjectInfo<>(new EnumerationRange(new EnumerationImpl<>(type))); } else { MetaClassImpl rangeClass = (MetaClassImpl) session.getClass(type); if (rangeClass != null) { return new MetadataObjectInfo<>(new ClassRange(rangeClass)); } else { return new MetadataObjectInfo<>(null, Collections.singletonList(new RangeInitTask(metaProperty, type, map))); } } }
From source file:de.mpg.imeji.logic.vo.Item.java
/** * Copy all {@link Fields} of an {@link Item} (including {@link Metadata}) to the current * {@link Item}/* w w w. jav a2 s . co m*/ * * @param copyFrom */ protected void copyInFields(Item copyFrom) { final Class<? extends Item> copyFromClass = copyFrom.getClass(); final Class<? extends Item> copyToClass = this.getClass(); for (final Method methodFrom : copyFromClass.getDeclaredMethods()) { String setMethodName = null; if (methodFrom.getName().startsWith("get")) { setMethodName = "set" + methodFrom.getName().substring(3, methodFrom.getName().length()); } else if (methodFrom.getName().startsWith("is")) { setMethodName = "set" + methodFrom.getName().substring(2, methodFrom.getName().length()); } if (setMethodName != null) { try { final Method methodTo = copyToClass.getMethod(setMethodName, methodFrom.getReturnType()); try { methodTo.invoke(this, methodFrom.invoke(copyFrom, (Object) null)); } catch (final Exception e) { // LOGGER.error("Could not copy field from method: " + // methodFrom.getName(), e); } } // No setter, do nothing. catch (final NoSuchMethodException e) { } } } }
From source file:com.nginious.http.serialize.JsonDeserializerCreator.java
/** * Creates a JSON deserializer for the specified bean class unless a deserializer has already * been created. Created deserializers are cached and returned on subsequent calls to this method. * /* www .j a v a2s.c o m*/ * @param <T> class type for bean * @param beanClazz bean class for which a deserializer should be created * @return the created deserializer * @throws SerializerFactoryException if unable to create deserializer or class is not a bean */ @SuppressWarnings("unchecked") protected <T> JsonDeserializer<T> create(Class<T> beanClazz) throws SerializerFactoryException { JsonDeserializer<T> deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } try { synchronized (this) { deserializer = (JsonDeserializer<T>) deserializers.get(beanClazz); if (deserializer != null) { return deserializer; } checkDeserializability(beanClazz, "json"); String intBeanClazzName = Serialization.createInternalClassName(beanClazz); Method[] methods = beanClazz.getMethods(); String intDeserializerClazzName = new StringBuffer(intBeanClazzName).append("JsonDeserializer") .toString(); // Create class ClassWriter writer = new ClassWriter(0); String signature = Serialization .createClassSignature("com/nginious/http/serialize/JsonDeserializer", intBeanClazzName); writer.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, intDeserializerClazzName, signature, "com/nginious/http/serialize/JsonDeserializer", null); // Create constructor Serialization.createConstructor(writer, "com/nginious/http/serialize/JsonDeserializer"); // Create deserialize method MethodVisitor visitor = createDeserializeMethod(writer, intBeanClazzName); for (Method method : methods) { Serializable info = method.getAnnotation(Serializable.class); boolean canDeserialize = info == null || (info != null && info.deserialize() && info.types().indexOf("json") > -1); if (canDeserialize && method.getName().startsWith("set") && method.getReturnType().equals(void.class) && method.getParameterTypes().length == 1) { Class<?>[] parameterTypes = method.getParameterTypes(); Class<?> parameterType = parameterTypes[0]; if (parameterType.isArray()) { Class<?> arrayType = parameterType.getComponentType(); if (arrayType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBooleanArray", "[Z", "[Z", intBeanClazzName, method.getName()); } else if (arrayType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDoubleArray", "[D", "[D", intBeanClazzName, method.getName()); } else if (arrayType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloatArray", "[F", "[F", intBeanClazzName, method.getName()); } else if (arrayType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeIntArray", "[I", "[I", intBeanClazzName, method.getName()); } else if (arrayType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLongArray", "[J", "[J", intBeanClazzName, method.getName()); } else if (arrayType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShortArray", "[S", "[S", intBeanClazzName, method.getName()); } else if (arrayType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeStringArray", "[Ljava/lang/String;", "[Ljava/lang/String;", intBeanClazzName, method.getName()); } } else if (parameterType.isPrimitive()) { if (parameterType.equals(boolean.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeBoolean", "Z", "Z", intBeanClazzName, method.getName()); } else if (parameterType.equals(double.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDouble", "D", "D", intBeanClazzName, method.getName()); } else if (parameterType.equals(float.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeFloat", "F", "F", intBeanClazzName, method.getName()); } else if (parameterType.equals(int.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeInt", "I", "I", intBeanClazzName, method.getName()); } else if (parameterType.equals(long.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeLong", "J", "J", intBeanClazzName, method.getName()); } else if (parameterType.equals(short.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeShort", "S", "S", intBeanClazzName, method.getName()); } } else if (parameterType.equals(Calendar.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeCalendar", "Ljava/util/Calendar;", "Ljava/util/Calendar;", intBeanClazzName, method.getName()); } else if (parameterType.equals(Date.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeDate", "Ljava/util/Date;", "Ljava/util/Date;", intBeanClazzName, method.getName()); } else if (parameterType.equals(String.class)) { createPropertyDeserializationCode(visitor, intDeserializerClazzName, "deserializeString", "Ljava/lang/String;", "Ljava/lang/String;", intBeanClazzName, method.getName()); } } } visitor.visitVarInsn(Opcodes.ALOAD, 3); visitor.visitInsn(Opcodes.ARETURN); visitor.visitMaxs(5, 4); visitor.visitEnd(); writer.visitEnd(); byte[] clazzBytes = writer.toByteArray(); ClassLoader controllerLoader = null; if (classLoader.hasLoaded(beanClazz)) { controllerLoader = beanClazz.getClassLoader(); } else { controllerLoader = this.classLoader; } Class<?> clazz = Serialization.loadClass(controllerLoader, intDeserializerClazzName.replace('/', '.'), clazzBytes); deserializer = (JsonDeserializer<T>) clazz.newInstance(); deserializers.put(beanClazz, deserializer); return deserializer; } } catch (IllegalAccessException e) { throw new SerializerFactoryException(e); } catch (InstantiationException e) { throw new SerializerFactoryException(e); } }
From source file:com.kelveden.rastajax.core.ResourceClassLoader.java
private ResourceClassMethod loadMethod(final Class<?> candidateResourceClass, final Method method) { final String logPrefix = " |-"; LOGGER.debug("{} Attempting to load method {} as a JAX-RS resource method...", logPrefix, method.getName()); String requestMethodDesignator = null; String uriTemplate = null;//from w w w . j av a 2 s .c o m String[] produces = null; String[] consumes = null; Class<?> returnType = method.getReturnType(); final Set<Annotation> methodAnnotations = JaxRsAnnotationScraper .scrapeJaxRsAnnotationsFrom(candidateResourceClass, method); LOGGER.debug("{} Found method annotations {}.", logPrefix, methodAnnotations.toString()); if (returnType != null) { LOGGER.debug("{} Method return type is {}.", logPrefix, returnType.getName()); } for (Annotation annotation : methodAnnotations) { final HttpMethod httpMethodAnnotation = annotation.annotationType().getAnnotation(HttpMethod.class); if (httpMethodAnnotation != null) { requestMethodDesignator = httpMethodAnnotation.value(); LOGGER.debug("{} Method request method designator is '{}'.", logPrefix, requestMethodDesignator); } else if (annotation.annotationType() == Path.class) { uriTemplate = ((Path) annotation).value(); LOGGER.debug("{} Method URI template '{}'.", logPrefix, uriTemplate); } else if (annotation.annotationType() == Produces.class) { produces = ((Produces) annotation).value(); LOGGER.debug("{} Method produces: {}.", logPrefix, StringUtils.join(produces, ",")); } else if (annotation.annotationType() == Consumes.class) { consumes = ((Consumes) annotation).value(); LOGGER.debug("{} Method consumes: {}.", logPrefix, StringUtils.join(consumes, ",")); } } if ((uriTemplate == null) && (requestMethodDesignator == null)) { LOGGER.debug("{} Method is NOT a resource method.", logPrefix); return null; } LOGGER.debug("{} Method is a resource method.", logPrefix); LOGGER.debug("{} Finding method parameters...", logPrefix); final List<Parameter> parameters = loadMethodParameters(candidateResourceClass, method); return createResourceClassMethod(method, uriTemplate, requestMethodDesignator, arrayAsList(consumes), arrayAsList(produces), parameters); }