List of usage examples for java.lang.reflect Method getReturnType
public Class<?> getReturnType()
From source file:com.tugo.dt.PojoUtils.java
/** * Return the getter expression for the given field. * <p>//from ww w . j a v a2 s . co m * If the field is a public member, the field name is used else the getter function. If no matching field or getter * method is found, the expression is returned unmodified. * * @param pojoClass class to check for the field * @param fieldExpression field name expression * @param exprClass expected field type * @return java code fragment */ private static String getSingleFieldGetterExpression(final Class<?> pojoClass, final String fieldExpression, final Class<?> exprClass) { JavaStatement code = new JavaReturnStatement( pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32, exprClass); code.appendCastToTypeExpr(pojoClass, OBJECT).append("."); try { final Field field = pojoClass.getField(fieldExpression); if (ClassUtils.isAssignable(field.getType(), exprClass)) { return code.append(field.getName()).getStatement(); } logger.debug("Field {} can not be assigned to an {}. Proceeding to locate a getter method.", field, exprClass); } catch (NoSuchFieldException ex) { logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass, fieldExpression); } catch (SecurityException ex) { logger.debug("{} does not have field {}. Proceeding to locate a getter method.", pojoClass, fieldExpression); } String methodName = GET + upperCaseWord(fieldExpression); try { Method method = pojoClass.getMethod(methodName); if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) { return code.append(methodName).append("()").getStatement(); } logger.debug( "method {} of the {} returns {} that can not be assigned to an {}. Proceeding to locate another getter method.", pojoClass, methodName, method.getReturnType(), exprClass); } catch (NoSuchMethodException ex) { logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass, methodName); } catch (SecurityException ex) { logger.debug("{} does not have method {}. Proceeding to locate another getter method.", pojoClass, methodName); } methodName = IS + upperCaseWord(fieldExpression); try { Method method = pojoClass.getMethod(methodName); if (ClassUtils.isAssignable(method.getReturnType(), exprClass)) { return code.append(methodName).append("()").getStatement(); } logger.debug( "method {} of the {} returns {} that can not be assigned to an {}. Proceeding with the original expression {}.", pojoClass, methodName, method.getReturnType(), exprClass, fieldExpression); } catch (NoSuchMethodException ex) { logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass, methodName, fieldExpression); } catch (SecurityException ex) { logger.debug("{} does not have method {}. Proceeding with the original expression {}.", pojoClass, methodName, fieldExpression); } return code.append(fieldExpression).getStatement(); }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
private static boolean isComplex(Method method, ColumnMetadata foreignReference) { return isComplex(method.getReturnType(), method, foreignReference); }
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
private static int getColumnType(Method method, ColumnMetadata foreignReference) { return getColumnType(method.getReturnType(), method, foreignReference); }
From source file:com.taobao.rpc.doclet.RPCAPIInfoHelper.java
/** * ?// w w w . j a v a 2s . c om * * @param method * @return */ public static Object buildTypeStructure(Class<?> type, Type genericType, Type oriGenericType) { if ("void".equalsIgnoreCase(type.getName()) || ClassUtils.isPrimitiveOrWrapper(type) || String.class.isAssignableFrom(type) || Date.class.isAssignableFrom(type) || URL.class.isAssignableFrom(type)) { // return type.getName().replaceAll("java.lang.", "").replaceAll("java.util.", "").replaceAll("java.sql.", ""); } // end if if (type.isArray()) { // return new Object[] { buildTypeStructure(type.getComponentType(), type.getComponentType(), genericType) }; } // end if if (ClassUtils.isAssignable(Map.class, type)) { // Map return Map.class.getName(); } // end if if (type.isEnum()) { // Enum return Enum.class.getName(); } // end if boolean isCollection = type != null ? Collection.class.isAssignableFrom(type) : false; if (isCollection) { Type rawType = type; if (genericType != null) { if (genericType instanceof ParameterizedType) { ParameterizedType _type = (ParameterizedType) genericType; Type[] actualTypeArguments = _type.getActualTypeArguments(); rawType = actualTypeArguments[0]; } else if (genericType instanceof GenericArrayType) { rawType = ((GenericArrayType) genericType).getGenericComponentType(); } if (genericType instanceof WildcardType) { rawType = ((WildcardType) genericType).getUpperBounds()[0]; } } if (rawType == type) { return new Object[] { rawType.getClass().getName() }; } else { if (rawType.getClass().isAssignableFrom(TypeVariableImpl.class)) { return new Object[] { buildTypeStructure( (Class<?>) ((ParameterizedType) oriGenericType).getActualTypeArguments()[0], rawType, genericType) }; } else { if (rawType instanceof ParameterizedType) { if (((ParameterizedType) rawType).getRawType() == Map.class) { return new Object[] { Map.class.getName() }; } } if (oriGenericType == rawType) { return new Object[] { rawType.getClass().getName() }; } return new Object[] { buildTypeStructure((Class<?>) rawType, rawType, genericType) }; } } } if (type.isInterface()) { return type.getName(); } ClassInfo paramClassInfo = RPCAPIDocletUtil.getClassInfo(type.getName()); //added if (null == paramClassInfo) { System.out.println("failed to get paramClassInfo for :" + type.getName()); return null; } List<FieldInfo> typeConstructure = new ArrayList<FieldInfo>(); BeanWrapper bean = new BeanWrapperImpl(type); PropertyDescriptor[] propertyDescriptors = bean.getPropertyDescriptors(); Method readMethod; String name; for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { readMethod = propertyDescriptor.getReadMethod(); if (readMethod == null || "getClass".equals(readMethod.getName())) { continue; } name = propertyDescriptor.getName(); FieldInfo fieldInfo = paramClassInfo.getFieldInfo(name); if (readMethod.getReturnType().isAssignableFrom(type)) { String comment = "structure is the same with parent."; typeConstructure .add(FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", comment)); } else { typeConstructure.add( FieldInfo.create(name, fieldInfo != null ? fieldInfo.getComment() : "", buildTypeStructure( readMethod.getReturnType(), readMethod.getGenericReturnType(), genericType))); } // end if } return typeConstructure; }
From source file:com.lucidtechnics.blackboard.TargetConstructor.java
private final static void printMethods(Class _class) { List methodList = new ArrayList(); Enhancer.getMethods(_class, null, methodList); Predicate mutatorPredicate = new Predicate() { public boolean evaluate(Object _object) { Method method = (Method) _object; if (logger.isDebugEnabled() == true) { logger.debug("Printing out specifics for method: " + method.getName() + " with return type: " + method.getReturnType().getName()); }/*from w w w .j a v a 2 s .c o m*/ for (int i = 0; i < method.getParameterTypes().length; i++) { if (logger.isDebugEnabled() == true) { logger.debug("and with parameter type: " + method.getParameterTypes()[i]); } } return true; } }; CollectionUtils.filter(methodList, mutatorPredicate); }
From source file:com.kamuda.common.exception.ExceptionUtils.java
/** * <p>Checks whether this <code>Throwable</code> class can store a cause.</p> * /*from w w w .java 2s .c o m*/ * <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], 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.genologics.ri.userdefined.UDF.java
/** * Helper method to get the collection of UDFs from an object. * * @param thing The object that should have the UDFs. * * @return The collection of UDFs from {@code thing}. * * @throws IllegalArgumentException if {@code thing} is null, or if {@code thing} * does not have a publicly visible "getUserDefinedFields" method returning a {@code Collection}. *//* ww w . j a va2 s . c o m*/ static Collection<UDF> getUDFCollection(Object thing) { if (thing == null) { throw new IllegalArgumentException("thing cannot be null"); } Method getPropsMethod = classUdfMethods.get(thing.getClass()); if (getPropsMethod == null) { try { getPropsMethod = thing.getClass().getMethod(UDF_METHOD_NAME); if (!Collection.class.isAssignableFrom(getPropsMethod.getReturnType())) { throw new IllegalArgumentException( MessageFormat.format("The \"{0}\" method on {1} does not return a Collection.", UDF_METHOD_NAME, thing.getClass().getName())); } classUdfMethods.put(thing.getClass(), getPropsMethod); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(MessageFormat.format("There is no method \"{0}\" method on {1}.", UDF_METHOD_NAME, thing.getClass().getName())); } } try { @SuppressWarnings("unchecked") Collection<UDF> udfs = (Collection<UDF>) getPropsMethod.invoke(thing); return udfs; } catch (IllegalAccessException e) { throw new IllegalArgumentException(MessageFormat.format("Cannot call method \"{0}\" method on {1}: {2}", UDF_METHOD_NAME, thing.getClass().getName(), e.getMessage())); } catch (InvocationTargetException e) { throw new RuntimeException("Exception while fetching UDFs from " + thing.getClass().getName(), e.getTargetException()); } }
From source file:com.mani.cucumber.ReflectionUtils.java
private static Object digInObject(Object target, String field) { Method getter = findAccessor(target, field); if (getter == null) { throw new IllegalStateException( "No accessor found for '" + field + "' found in class " + target.getClass().getName()); }/*from w ww . j a v a 2 s .c o m*/ try { Object obj = getter.invoke(target); if (obj == null) { obj = getter.getReturnType().newInstance(); Method setter = findMethod(target, "set" + field, obj.getClass()); setter.invoke(target, obj); } return obj; } catch (InstantiationException exception) { throw new IllegalStateException("Unable to create a new instance", exception); } catch (IllegalAccessException exception) { throw new IllegalStateException("Unable to access getter, setter, or constructor", exception); } catch (InvocationTargetException exception) { if (exception.getCause() instanceof RuntimeException) { throw (RuntimeException) exception.getCause(); } throw new IllegalStateException("Checked exception thrown from getter or setter method", exception); } }
From source file:com.p5solutions.mapping.EntityMapper.java
/** * Run./*from w ww . j a va 2s . c o m*/ * * @param value * the value * @param target * the target * @param path * the path */ protected static final void run(Object value, Object target, String path) { // determine the path and create the // necessary objects by the dot separation Class<?> clazz = target.getClass(); Object pushInstance = null; int pos = path.indexOf('.', 1); String field = path; // TODO make sure that we want to ignore creation of embedded objects // when the source value is null, for example, address.country == null // should we create target.setAddress(new Address())? then // set the address.country = null? this could be problematic for persistence // if the value of the entire embedded object is null, as such throwing // a javax.persistence validation exception and or database null constraint if (pos > 0 && value != null) { field = path.substring(0, pos); String next = path.substring(pos + 1); Method push = ReflectionUtility.findGetterMethod(clazz, field); if (push != null) { Class<?> pushType = push.getReturnType(); pushInstance = ReflectionUtility.getValue(field, target); // if the instance has not been initialized then set it if (pushInstance == null) { pushInstance = ReflectionUtility.newInstance(pushType); } // recursion until we set the appropriate value run(value, pushInstance, next); // set teh instance to the current target ReflectionUtility.setValue(field, target, pushInstance); } } else { ReflectionUtility.setValue(field, target, value); } }
From source file:com.facebook.GraphObjectWrapper.java
private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) { if (hasClassBeenVerified(graphObjectClass)) { return;//from w w w . j a v a2 s . co m } if (!graphObjectClass.isInterface()) { throw new FacebookGraphObjectException( "GraphObjectWrapper can only wrap interfaces, not class: " + graphObjectClass.getName()); } Method[] methods = graphObjectClass.getMethods(); for (Method method : methods) { String methodName = method.getName(); int parameterCount = method.getParameterTypes().length; Class<?> returnType = method.getReturnType(); boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class); if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) { // Don't worry about any methods from GraphObject or one of its base classes. continue; } else if (parameterCount == 1 && returnType == Void.TYPE) { if (hasPropertyNameOverride) { // If a property override is present, it MUST be valid. We don't fallback // to using the method name if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) { continue; } } else if (methodName.startsWith("set") && methodName.length() > 3) { // Looks like a valid setter continue; } } else if (parameterCount == 0 && returnType != Void.TYPE) { if (hasPropertyNameOverride) { // If a property override is present, it MUST be valid. We don't fallback // to using the method name if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) { continue; } } else if (methodName.startsWith("get") && methodName.length() > 3) { // Looks like a valid getter continue; } } throw new FacebookGraphObjectException("GraphObjectWrapper can't proxy method: " + method.toString()); } recordClassHasBeenVerified(graphObjectClass); }