List of usage examples for java.lang.reflect Method getReturnType
public Class<?> getReturnType()
From source file:gov.nih.nci.caarray.util.CaArrayUtils.java
/** * For given class, returns a ReflectionHelper instance with property accessors for the class. * /*from ww w . j a v a2 s .c o m*/ * @param clazz the class * @return the ReflectionHelper */ public static ReflectionHelper createReflectionHelper(Class<?> clazz) { final List<PropertyAccessor> accessors = new ArrayList<PropertyAccessor>(); Class<?> currentClass = clazz; while (currentClass != null) { final Method[] methods = currentClass.getDeclaredMethods(); for (final Method getter : methods) { if (getter.getName().startsWith("get") && getter.getParameterTypes().length == 0) { for (final Method setter : methods) { if (setter.getName().equals('s' + getter.getName().substring(1)) && setter.getParameterTypes().length == 1 && Void.TYPE.equals(setter.getReturnType()) && getter.getReturnType().equals(setter.getParameterTypes()[0])) { getter.setAccessible(true); setter.setAccessible(true); accessors.add(new PropertyAccessor(getter, setter)); } } } } currentClass = currentClass.getSuperclass(); } return new ReflectionHelper(accessors.toArray(new PropertyAccessor[accessors.size()])); }
From source file:com.free.exception.ExceptionHelper.java
/** * <p>//from w ww.j a v a2 s .c o m * Checks whether this <code>Throwable</code> class can store a cause. * </p> * <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(); for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) { try { Method method = cls.getMethod(CAUSE_METHOD_NAMES[i], (Class[]) null); if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) { return true; } } catch (NoSuchMethodException ignored) { } catch (SecurityException ignored) { } } try { Field field = cls.getField("detail"); if (field != null) { return true; } } catch (NoSuchFieldException ignored) { } catch (SecurityException ignored) { } return false; }
From source file:com.evolveum.midpoint.util.ReflectionUtil.java
/** * Try to get java property from the object by reflection *//*from ww w . j a va 2 s .c o m*/ public static <T> T getJavaProperty(Object object, String propertyName, Class<T> propetyClass) { String getterName = getterName(propertyName); Method method; try { method = object.getClass().getMethod(getterName); } catch (SecurityException e) { throw new IllegalArgumentException( "Security error getting getter for property " + propertyName + ": " + e.getMessage(), e); } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "No getter for property " + propertyName + " in " + object + " (" + object.getClass() + ")"); } if (method == null) { throw new IllegalArgumentException( "No getter for property " + propertyName + " in " + object + " (" + object.getClass() + ")"); } if (!propetyClass.isAssignableFrom(method.getReturnType())) { throw new IllegalArgumentException( "The getter for property " + propertyName + " returns " + method.getReturnType() + ", expected " + propetyClass + " in " + object + " (" + object.getClass() + ")"); } try { return (T) method.invoke(object); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( "Error invoking getter for property " + propertyName + " in " + object + " (" + object.getClass() + "): " + e.getClass().getSimpleName() + ": " + e.getMessage(), e); } catch (IllegalAccessException e) { throw new IllegalArgumentException( "Error invoking getter for property " + propertyName + " in " + object + " (" + object.getClass() + "): " + e.getClass().getSimpleName() + ": " + e.getMessage(), e); } catch (InvocationTargetException e) { throw new IllegalArgumentException( "Error invoking getter for property " + propertyName + " in " + object + " (" + object.getClass() + "): " + e.getClass().getSimpleName() + ": " + e.getMessage(), e); } }
From source file:io.coala.json.DynaBean.java
/** * @param referenceType/*from ww w . j av a 2s . co m*/ * @param <S> * @param <T> * @return */ static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType, final Properties... imports) { return new JsonDeserializer<T>() { @Override public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt, final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException { return deserialize(jp, ctxt); } @Override public T deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException { if (jp.getCurrentToken() == JsonToken.VALUE_NULL) return null; // if( Wrapper.class.isAssignableFrom( resultType ) ) // { // // FIXME // LOG.trace( "deser wrapper intf of {}", jp.getText() ); // return (T) Wrapper.Util.valueOf( jp.getText(), // resultType.asSubclass( Wrapper.class ) ); // } if (Config.class.isAssignableFrom(resultType)) { final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() { }); final Iterator<Entry<String, Object>> it = entries.entrySet().iterator(); for (Entry<String, Object> next = null; it.hasNext(); next = it.next()) if (next != null && next.getValue() == null) { LOG.trace("Ignoring null value: {}", next); it.remove(); } return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries)); } // else if (Config.class.isAssignableFrom(resultType)) // throw new JsonGenerationException( // "Config does not extend "+Mutable.class.getName()+" required for deserialization: " // + Arrays.asList(resultType // .getInterfaces())); // can't parse directly to interface type final DynaBean bean = new DynaBean(); final TreeNode tree = jp.readValueAsTree(); // override attributes as defined in interface getters final Set<String> attributes = new HashSet<>(); for (Method method : resultType.getMethods()) { if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0) continue; final String attribute = method.getName(); if (attribute.equals("toString") || attribute.equals("hashCode")) continue; attributes.add(attribute); final TreeNode value = tree.get(attribute);// bean.any().get(attributeName); if (value == null) continue; bean.set(method.getName(), om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports))); } if (tree.isObject()) { // keep superfluous properties as TreeNodes, just in case final Iterator<String> fieldNames = tree.fieldNames(); while (fieldNames.hasNext()) { final String fieldName = fieldNames.next(); if (!attributes.contains(fieldName)) bean.set(fieldName, tree.get(fieldName)); } } else if (tree.isValueNode()) { for (Class<?> type : resultType.getInterfaces()) for (Method method : type.getDeclaredMethods()) { // LOG.trace( "Scanning {}", method ); if (method.isAnnotationPresent(JsonProperty.class)) { final String property = method.getAnnotation(JsonProperty.class).value(); // LOG.trace( "Setting {}: {}", property, // ((ValueNode) tree).textValue() ); bean.set(property, ((ValueNode) tree).textValue()); } } } else throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType, tree.getClass()); return DynaBean.proxyOf(om, resultType, bean, imports); } }; }
From source file:com.springframework.core.annotation.AnnotationUtils.java
/** * Retrieve the given annotation's attributes as an {@link AnnotationAttributes} * map structure./*from www . jav a2 s . c o m*/ * <p>This method provides fully recursive annotation reading capabilities on par with * the reflection-based {@link org.springframework.core.type.StandardAnnotationMetadata}. * @param annotation the annotation to retrieve the attributes for * @param classValuesAsString whether to convert Class references into Strings (for * compatibility with {@link org.springframework.core.type.AnnotationMetadata}) * or to preserve them as Class references * @param nestedAnnotationsAsMap whether to turn nested Annotation instances into * {@link AnnotationAttributes} maps (for compatibility with * {@link org.springframework.core.type.AnnotationMetadata}) or to preserve them as * Annotation instances * @return the annotation attributes (a specialized Map) with attribute names as keys * and corresponding attribute values as values; never {@code null} * @since 3.1.1 */ public static AnnotationAttributes getAnnotationAttributes(Annotation annotation, boolean classValuesAsString, boolean nestedAnnotationsAsMap) { AnnotationAttributes attrs = new AnnotationAttributes(); Method[] methods = annotation.annotationType().getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class) { try { ReflectionUtils.makeAccessible(method); Object value = method.invoke(annotation); attrs.put(method.getName(), adaptValue(value, classValuesAsString, nestedAnnotationsAsMap)); } catch (Exception ex) { throw new IllegalStateException("Could not obtain annotation attribute values", ex); } } } return attrs; }
From source file:com.softmotions.commons.bean.BeanUtils.java
/** * Gets a property from the given bean.//from w w w .j av a 2 s.co m * * @param clazz The class to determine the property type for. * @param propertyName The name of the property to read. * @param lenient If true is passed for this attribute, null will returned for * in case no matching getter method is defined, else an Exception will be throw * in this case. * @return The determined value. * @throws BeanException In case the bean access failed. */ public static Class getPropertyType(Class clazz, String propertyName, boolean lenient) throws BeanException { try { // getting property object from bean using "getNnnn", where nnnn is parameter name Method getterMethod = null; try { // first trying form getPropertyNaae for regular value String getterName = "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); getterMethod = clazz.getMethod(getterName, GETTER_ARG_TYPES); } catch (NoSuchMethodException ex) { // next trying isPropertyNaae for possible boolean String getterName = "is" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1); getterMethod = clazz.getMethod(getterName, GETTER_ARG_TYPES); } return getterMethod.getReturnType(); } catch (NoSuchMethodError | NoSuchMethodException ex) { if (!lenient) { throw new BeanException("Property '" + propertyName + "' is undefined for given bean from class " + clazz.getName() + "."); } } return null; }
From source file:com.dianping.resource.io.util.ReflectionUtils.java
/** * Get the unique set of declared methods on the leaf class and all superclasses. Leaf * class methods are included first and while traversing the superclass hierarchy any methods found * with signatures matching a method already included are filtered out. */// www .j a va2s. c om public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // Is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); }
From source file:com.kcs.core.utilities.Utility.java
public static Object clone(Object sourceObject, Object tarObject) { if (sourceObject != null) { Class theSourceClass = sourceObject.getClass(); Class targetClass = tarObject.getClass(); Method soruceMethods[] = theSourceClass.getMethods(); for (int i = 0; i < soruceMethods.length; i++) { Method method = soruceMethods[i]; try { if (method.getName().startsWith("get") && !"getClass".equalsIgnoreCase(method.getName())) { if (method.getName().equalsIgnoreCase("getId")) { Object idObj = method.invoke(sourceObject); Class idClass = idObj.getClass(); Method idMethods[] = idClass.getMethods(); for (int j = 0; j < idMethods.length; j++) { try { Method idMethod = idMethods[j]; if (idMethod.getName().startsWith("get") && !"getClass".equals(idMethod.getName())) { String setterName = idMethod.getName().substring(3); setterName = "set" + setterName.substring(0, 1).toUpperCase() + setterName.substring(1); Method setter = targetClass.getMethod(setterName, idMethod.getReturnType()); setter.invoke(tarObject, idMethod.invoke(idObj)); }//from w ww.j a v a2 s . co m } catch (Exception e) { } } } else { String setterName = method.getName().substring(3); setterName = "set" + setterName.substring(0, 1).toUpperCase() + setterName.substring(1); Method setter = targetClass.getMethod(setterName, method.getReturnType()); setter.invoke(tarObject, method.invoke(sourceObject)); } } } catch (Exception e) { //e.printStackTrace(); } } return tarObject; } else { return null; } }
From source file:com.xiongyingqi.util.ReflectionUtils.java
/** * Get the unique set of declared methods on the leaf class and all superclasses. Leaf * class methods are included first and while traversing the superclass hierarchy any methods found * with signatures matching a method already included are filtered out. *//*from w w w .ja va2s . co m*/ public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { @Override public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); }
From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java
/** * Get the unique set of declared methods on the leaf class and all superclasses. Leaf * class methods are included first and while traversing the superclass hierarchy any methods found * with signatures matching a method already included are filtered out. *//*from w w w . j a v a 2s .c o m*/ public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException { final List<Method> methods = new ArrayList<Method>(32); doWithMethods(leafClass, new MethodCallback() { public void doWith(Method method) { boolean knownSignature = false; Method methodBeingOverriddenWithCovariantReturnType = null; for (Method existingMethod : methods) { if (method.getName().equals(existingMethod.getName()) && Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) { // Is this a covariant return type situation? if (existingMethod.getReturnType() != method.getReturnType() && existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) { methodBeingOverriddenWithCovariantReturnType = existingMethod; } else { knownSignature = true; } break; } } if (methodBeingOverriddenWithCovariantReturnType != null) { methods.remove(methodBeingOverriddenWithCovariantReturnType); } if (!knownSignature && !isCglibRenamedMethod(method)) { methods.add(method); } } }); return methods.toArray(new Method[methods.size()]); }