Example usage for java.lang.reflect Method getReturnType

List of usage examples for java.lang.reflect Method getReturnType

Introduction

In this page you can find the example usage for java.lang.reflect Method getReturnType.

Prototype

public Class<?> getReturnType() 

Source Link

Document

Returns a Class object that represents the formal return type of the method represented by this Method object.

Usage

From source file:ch.digitalfondue.npjt.QueryFactory.java

@SuppressWarnings("unchecked")
public <T> T from(final Class<T> clazz) {

    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new InvocationHandler() {
        @Override// w  ww  .j a v  a  2  s . c  om
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            boolean hasAnnotation = method.getAnnotation(Query.class) != null;
            if (hasAnnotation) {
                QueryTypeAndQuery qs = extractQueryAnnotation(clazz, method);
                return qs.type.apply(qs.query, qs.rowMapperClass, jdbc, method, args, columnMapperFactories.set,
                        parameterConverters.set);
            } else if (method.getReturnType().equals(NamedParameterJdbcTemplate.class) && args == null) {
                return jdbc;
            } else if (IS_DEFAULT_METHOD != null && (boolean) IS_DEFAULT_METHOD.invoke(method)) {
                final Class<?> declaringClass = method.getDeclaringClass();
                return LOOKUP_CONSTRUCTOR.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE)
                        .unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
            } else {
                throw new IllegalArgumentException(
                        String.format("missing @Query annotation for method %s in interface %s",
                                method.getName(), clazz.getSimpleName()));
            }

        }
    }

    );
}

From source file:com.comphenix.protocol.reflect.FuzzyReflection.java

/**
 * Retrieves every method that has the given parameter types and return type.
 * @param returnType - return type of the method to find.
 * @param args - parameter types of the method to find.
 * @return Every method that satisfies the given constraints.
 *///from   w  w  w  .  ja v a2  s.  c  om
public List<Method> getMethodListByParameters(Class<?> returnType, Class<?>[] args) {
    List<Method> methods = new ArrayList<Method>();

    // Find the correct method to call
    for (Method method : getMethods()) {
        if (method.getReturnType().equals(returnType) && Arrays.equals(method.getParameterTypes(), args)) {
            methods.add(method);
        }
    }
    return methods;
}

From source file:com.infinities.skyport.async.impl.AsyncHandler.java

@Override
protected Object handleInvocation(Object proxy, Method method, final Object[] args) throws Throwable {
    Object support = TaskType.getSupport(taskType, inner);
    if ("getSupport".equals(method.getName()) && args.length == 0) {
        return support;
    }//  w w  w . j a  va2 s  .  co  m
    final Method innerMethod = AsyncHandler.getMethod(support, method.getName(), method.getParameterTypes());
    PoolSize poolSize = PoolSize.SHORT;
    String methodName = method.getName();

    if (!AsyncResult.class.equals(method.getReturnType())) {
        return innerMethod.invoke(inner, args);
    }

    TaskEvent event = TaskEvent.getInitializedEvent(null, method.getName(), configurationId);
    taskEventHome.persist(event);
    TaskEventLog log = new TaskEventLog(event, new Date(), Status.Initiazing, "Task is initialized", null);
    taskEventLogHome.persist(log);
    try {
        EntityManagerHelper.commitAndClose();
    } catch (Exception ex) {
        logger.warn("commit log failed, please check the database.", ex);
        throw ex;
    }

    // get pool size the method use.
    try {
        FunctionConfiguration functionConfiguration = (FunctionConfiguration) PropertyUtils
                .getProperty(configuration, methodName);
        poolSize = functionConfiguration.getPoolSize();
    } catch (Exception e) {
        throwCause(e, false);
        throw new AssertionError("can't get here");
    }

    DistributedExecutor pool = pools.getThreadPool(poolSize);

    // //save job;

    AsyncTaskImpl task = new AsyncTaskImpl();
    task.setArgs(args);
    task.setMethodName(method.getName());
    task.setServiceProvider(inner);
    task.setTaskType(taskType);
    task.setParameterTypes(method.getParameterTypes());

    try {
        ListenableFuture<Object> future = pool.submit(task);
        AsyncResult<Object> asyncResult = new AsyncResult<Object>(future);
        return asyncResult;
    } catch (Exception e) {
        try {
            ThrowableWrapper wrapper = new ThrowableWrapper(e);
            commitLog(Status.Fail, event.getId(), "Task has been rejected", wrapper);
            logger.error("encounter exception while schedule a task", e);
        } catch (Exception ex) {
            logger.warn("unexpected exception in callback obReject event", ex);
        }

        throw e;
    }

}

From source file:com.link_intersystems.lang.reflect.ReflectFacade.java

/**
 * {@inheritDoc} Transforms a {@link Method} into it's return type.
 *
 * @since 1.0.0.0//from ww  w  . j a  va2s. c  o m
 */
public Object transform(Object input) {
    Method method = (Method) input;
    return method.getReturnType();
}

From source file:com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBReflector.java

/**
 * Returns the setter corresponding to the getter given, or null if no such
 * setter exists./*from  ww  w  .j a v a  2s . co m*/
 */
Method getSetter(Method getter) {
    synchronized (setterCache) {
        if (!setterCache.containsKey(getter)) {
            String fieldName = ReflectionUtils.getFieldNameByGetter(getter, false);
            String setterName = "set" + fieldName;
            Method setter = null;
            try {
                setter = getter.getDeclaringClass().getMethod(setterName, getter.getReturnType());
            } catch (NoSuchMethodException e) {
                throw new DynamoDBMappingException("Expected a public, one-argument method called " + setterName
                        + " on class " + getter.getDeclaringClass(), e);
            } catch (SecurityException e) {
                throw new DynamoDBMappingException("No access to public, one-argument method called "
                        + setterName + " on class " + getter.getDeclaringClass(), e);
            }
            setterCache.put(getter, setter);
        }
        return setterCache.get(getter);
    }
}

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();//from  w  ww.j  av  a 2s  .co m
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

From source file:net.nelz.simplesm.aop.CacheBase.java

protected Method getKeyMethod(final Object keyObject) throws NoSuchMethodException {
    final Method storedMethod = methodStore.find(keyObject.getClass());
    if (storedMethod != null) {
        return storedMethod;
    }/*w w w.jav  a  2 s.  c  o m*/
    final Method[] methods = keyObject.getClass().getDeclaredMethods();
    Method targetMethod = null;
    for (final Method method : methods) {
        if (method != null && method.getAnnotation(CacheKeyMethod.class) != null) {
            if (method.getParameterTypes().length > 0) {
                throw new InvalidAnnotationException(
                        String.format("Method [%s] must have 0 arguments to be annotated with [%s]",
                                method.toString(), CacheKeyMethod.class.getName()));
            }
            if (!String.class.equals(method.getReturnType())) {
                throw new InvalidAnnotationException(
                        String.format("Method [%s] must return a String to be annotated with [%s]",
                                method.toString(), CacheKeyMethod.class.getName()));
            }
            if (targetMethod != null) {
                throw new InvalidAnnotationException(String.format(
                        "Class [%s] should have only one method annotated with [%s]. See [%s] and [%s]",
                        keyObject.getClass().getName(), CacheKeyMethod.class.getName(), targetMethod.getName(),
                        method.getName()));
            }
            targetMethod = method;
        }
    }

    if (targetMethod == null) {
        targetMethod = keyObject.getClass().getMethod("toString", null);
    }

    methodStore.add(keyObject.getClass(), targetMethod);

    return targetMethod;
}

From source file:com.jada.admin.AdminLookupDispatchAction.java

@SuppressWarnings("unchecked")
protected void encodeForm(ActionForm form)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException,
        NoSuchMethodException, SecurityException, NoSuchFieldException {
    Method methods[] = form.getClass().getDeclaredMethods();

    String encodeFields[] = {};/* w w w .ja v a2 s.  c  o  m*/
    try {
        Field field = form.getClass().getField("encodeFields");
        encodeFields = (String[]) field.get(form);
    } catch (java.lang.NoSuchFieldException e) {
    }

    for (Method m : methods) {
        if (!m.getName().startsWith("get")) {
            continue;
        }
        if (m.getParameterTypes().length > 0) {
            continue;
        }
        Class type = m.getReturnType();

        if (type.isArray()) {
            Object objects[] = (Object[]) m.invoke(form);
            if (objects != null) {
                for (Object object : objects) {
                    if (isActionForm(object.getClass())) {
                        encodeForm((ActionForm) object);
                    }
                }
            }
            continue;
        }

        if (isActionForm(type)) {
            ActionForm object = (ActionForm) m.invoke(form);
            encodeForm((ActionForm) object);
            continue;
        }

        if (type != String.class) {
            continue;
        }

        String fieldname = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4);
        boolean found = false;
        for (String f : encodeFields) {
            if (f.equals(fieldname)) {
                found = true;
                break;
            }
        }
        if (!found) {
            continue;
        }

        String value = (String) m.invoke(form);
        value = StringEscapeUtils.escapeHtml(value);

        String methodName = "set" + m.getName().substring(3);
        Class[] args = new Class[] { String.class };
        Method setMethod = form.getClass().getDeclaredMethod(methodName, args);
        setMethod.invoke(form, value);
    }

}

From source file:com.haulmont.restapi.service.EntitiesControllerManager.java

private Object getIdFromString(String entityId, MetaClass metaClass) {
    try {/*from   ww  w.  j  a  va  2 s .c o  m*/
        if (BaseDbGeneratedIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
            if (BaseIdentityIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                return IdProxy.of(Long.valueOf(entityId));
            } else if (BaseIntIdentityIdEntity.class.isAssignableFrom(metaClass.getJavaClass())) {
                return IdProxy.of(Integer.valueOf(entityId));
            } else {
                Class<?> clazz = metaClass.getJavaClass();
                while (clazz != null) {
                    Method[] methods = clazz.getDeclaredMethods();
                    for (Method method : methods) {
                        if (method.getName().equals("getDbGeneratedId")) {
                            Class<?> idClass = method.getReturnType();
                            if (Long.class.isAssignableFrom(idClass)) {
                                return Long.valueOf(entityId);
                            } else if (Integer.class.isAssignableFrom(idClass)) {
                                return Integer.valueOf(entityId);
                            } else if (Short.class.isAssignableFrom(idClass)) {
                                return Long.valueOf(entityId);
                            } else if (UUID.class.isAssignableFrom(idClass)) {
                                return UUID.fromString(entityId);
                            }
                        }
                    }
                    clazz = clazz.getSuperclass();
                }
            }
            throw new UnsupportedOperationException("Unsupported ID type in entity " + metaClass.getName());
        } else {
            //noinspection unchecked
            Method getIdMethod = metaClass.getJavaClass().getMethod("getId");
            Class<?> idClass = getIdMethod.getReturnType();
            if (UUID.class.isAssignableFrom(idClass)) {
                return UUID.fromString(entityId);
            } else if (Integer.class.isAssignableFrom(idClass)) {
                return Integer.valueOf(entityId);
            } else if (Long.class.isAssignableFrom(idClass)) {
                return Long.valueOf(entityId);
            } else {
                return entityId;
            }
        }
    } catch (Exception e) {
        throw new RestAPIException("Invalid entity ID",
                String.format("Cannot convert %s into valid entity ID", entityId), HttpStatus.BAD_REQUEST, e);
    }
}

From source file:com.msopentech.odatajclient.proxy.api.impl.EntitySetInvocationHandler.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 (method.getName().startsWith("new") && ArrayUtils.isEmpty(args)) {
        if (method.getName().endsWith("Collection")) {
            return newEntityCollection(method.getReturnType());
        } else {//  w  ww.j av a  2s  .  c o  m
            return newEntity(method.getReturnType());
        }
    } else {
        throw new UnsupportedOperationException("Method not found: " + method);
    }
}