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:com.perfect.autosdk.core.JsonProxy.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String addr = service.serverUrl + AddressUtil.getJsonAddr(interfaces) + '/' + method.getName();

    JsonConnection conn = new GZIPJsonConnection(addr);
    conn.setConnectTimeout(service.connectTimeoutMills);
    conn.setReadTimeout(service.readTimeoutMills);
    JsonEnvelop request = makeRequest(args[0]);
    conn.sendRequest(request);/*from w ww  .ja  v  a  2s.co  m*/
    JsonEnvelop<ResHeader, ?> response = conn.readResponse(ResHeader.class, method.getReturnType());
    ResHeader resHeader = response.getHeader();
    if (!resHeader.getFailures().isEmpty()) {
        if (log.isErrorEnabled()) {
            log.error("Call Error: Head info = " + resHeader + "\n" + "account info = " + service.getUsername()
                    + "\n" + "request info = " + addr + "\n" + "request param = " + args[0]);
        }
        if (resHeader.getFailures().get(0).getCode() == 8904) {
            Timer timer = new Timer("waitLock");
            final CountDownLatch latch = new CountDownLatch(1);
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("waiting....");
                    latch.countDown();
                }
            }, 15000);

            latch.await();
        }
    }
    ResHeaderUtil.resHeader.set(response.getHeader());
    BaiduApiQuota.setQuota(service.username, response.getHeader().getQuota());
    return response.getBody();
}

From source file:com.msopentech.odatajclient.proxy.api.impl.EntityTypeInvocationHandler.java

private Object getNavigationPropertyValue(final NavigationProperty property, final Method getter) {
    final Class<?> type = getter.getReturnType();
    final Class<?> collItemType;
    if (AbstractEntityCollection.class.isAssignableFrom(type)) {
        final Type[] entityCollectionParams = ((ParameterizedType) type.getGenericInterfaces()[0])
                .getActualTypeArguments();
        collItemType = (Class<?>) entityCollectionParams[0];
    } else {//from   w  w  w  .  jav  a 2s  . c  om
        collItemType = type;
    }

    final Object navPropValue;

    if (linkChanges.containsKey(property)) {
        navPropValue = linkChanges.get(property);
    } else {
        final ODataLink link = EngineUtils.getNavigationLink(property.name(), entity);
        if (link instanceof ODataInlineEntity) {
            // return entity
            navPropValue = getEntityProxy(((ODataInlineEntity) link).getEntity(), property.targetContainer(),
                    property.targetEntitySet(), type, false);
        } else if (link instanceof ODataInlineEntitySet) {
            // return entity set
            navPropValue = getEntityCollection(collItemType, type, property.targetContainer(),
                    ((ODataInlineEntitySet) link).getEntitySet(), link.getLink(), false);
        } else {
            // navigate
            final URI uri = URIUtils.getURI(containerHandler.getFactory().getServiceRoot(),
                    link.getLink().toASCIIString());

            if (AbstractEntityCollection.class.isAssignableFrom(type)) {
                navPropValue = getEntityCollection(collItemType, type, property.targetContainer(),
                        client.getRetrieveRequestFactory().getEntitySetRequest(uri).execute().getBody(), uri,
                        true);
            } else {
                final ODataRetrieveResponse<ODataEntity> res = client.getRetrieveRequestFactory()
                        .getEntityRequest(uri).execute();

                navPropValue = getEntityProxy(res.getBody(), property.targetContainer(),
                        property.targetEntitySet(), type, res.getEtag(), true);
            }
        }

        if (navPropValue != null) {
            int checkpoint = linkChanges.hashCode();
            linkChanges.put(property, navPropValue);
            updateLinksTag(checkpoint);
        }
    }

    return navPropValue;
}

From source file:cn.com.sinosoft.util.exception.ExceptionUtils.java

/**
 * <p>//from   ww w . ja  va 2s .c om
 * Finds a <code>Throwable</code> by method name.
 * </p>
 * 
 * @param throwable
 *            the exception to examine
 * @param methodName
 *            the name of the method to find and invoke
 * @return the wrapped exception, or <code>null</code> if not found
 */
private static Throwable getCauseUsingMethodName(Throwable throwable, String methodName) {
    Method method = null;
    try {
        Class<?>[] parameterTypes = {};
        method = throwable.getClass().getMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException ignored) {
        // exception ignored
    } catch (SecurityException ignored) {
        // exception ignored
    }

    if (method != null && Throwable.class.isAssignableFrom(method.getReturnType())) {
        try {
            return (Throwable) method.invoke(throwable, ArrayUtils.EMPTY_OBJECT_ARRAY);
        } catch (IllegalAccessException ignored) {
            // exception ignored
        } catch (IllegalArgumentException ignored) {
            // exception ignored
        } catch (InvocationTargetException ignored) {
            // exception ignored
        }
    }
    return null;
}

From source file:com.ween.learn.util.excel.ImportExcel.java

/**
 * ??/*from  w w  w .j av  a  2s .  com*/
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);
        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.weibo.api.motan.config.AbstractConfig.java

@Override
public String toString() {
    try {/* w  w w  . j  a  va 2  s . c  o m*/
        StringBuilder buf = new StringBuilder();
        buf.append("<motan:");
        buf.append(getTagName(getClass()));
        Method[] methods = getClass().getMethods();
        for (Method method : methods) {
            try {
                String name = method.getName();
                if ((name.startsWith("get") || name.startsWith("is")) && !"getClass".equals(name)
                        && !"get".equals(name) && !"is".equals(name) && Modifier.isPublic(method.getModifiers())
                        && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) {
                    int i = name.startsWith("get") ? 3 : 2;
                    String key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1);
                    Object value = method.invoke(this);
                    if (value != null) {
                        buf.append(" ");
                        buf.append(key);
                        buf.append("=\"");
                        buf.append(value);
                        buf.append("\"");
                    }
                }
            } catch (Exception e) {
                LoggerUtil.warn(e.getMessage(), e);
            }
        }
        buf.append(" />");
        return buf.toString();
    } catch (Throwable t) { // 
        LoggerUtil.warn(t.getMessage(), t);
        return super.toString();
    }
}

From source file:jenkins.scm.api.SCMHeadMixinEqualityGenerator.java

/**
 * Creates the {@link SCMHeadMixin.Equality} instance.
 *
 * @param type the {@link SCMHead} type to create the instance for.
 * @return the {@link SCMHeadMixin.Equality} instance.
 *//*from ww  w .j  a va2 s  .  c om*/
@NonNull
private SCMHeadMixin.Equality create(@NonNull Class<? extends SCMHead> type) {
    Map<String, Method> properties = new TreeMap<String, Method>();
    for (Class clazz : (List<Class>) ClassUtils.getAllInterfaces(type)) {
        if (!SCMHeadMixin.class.isAssignableFrom(clazz)) {
            // not a mix-in
            continue;
        }
        if (SCMHeadMixin.class == clazz) {
            // no need to check this by reflection
            continue;
        }
        if (!Modifier.isPublic(clazz.getModifiers())) {
            // not public
            continue;
        }
        // this is a mixin interface, only look at declared properties;
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getReturnType() == Void.class) {
                // nothing to do with us
                continue;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                // should never get here
                continue;
            }
            if (Modifier.isStatic(method.getModifiers())) {
                // might get here with Java 8
                continue;
            }
            if (method.getParameterTypes().length != 0) {
                // not a property
                continue;
            }
            String name = method.getName();
            if (!name.matches("^((is[A-Z0-9_].*)|(get[A-Z0-9_].*))$")) {
                // not a property
                continue;
            }
            if (name.startsWith("is")) {
                name = "" + Character.toLowerCase(name.charAt(2))
                        + (name.length() > 3 ? name.substring(3) : "");
            } else {
                name = "" + Character.toLowerCase(name.charAt(3))
                        + (name.length() > 4 ? name.substring(4) : "");
            }
            if (properties.containsKey(name)) {
                // a higher priority interface already defined the method
                continue;
            }
            properties.put(name, method);
        }
    }
    if (properties.isEmpty()) {
        // no properties to consider
        return new ConstantEquality();
    }
    if (forceReflection) {
        return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));
    }
    // now we define the class
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    String name = SCMHeadMixin.class.getPackage().getName() + ".internal." + type.getName();

    // TODO Move to 1.7 opcodes once baseline 1.612+
    cw.visit(Opcodes.V1_6, ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(SCMHeadMixin.Equality.class) });
    generateDefaultConstructor(cw);
    generateEquals(cw, properties.values());
    byte[] image = cw.toByteArray();

    Class<? extends SCMHeadMixin.Equality> c = defineClass(name, image, 0, image.length)
            .asSubclass(SCMHeadMixin.Equality.class);

    try {
        return c.newInstance();
    } catch (InstantiationException e) {
        // fallback to reflection
    } catch (IllegalAccessException e) {
        // fallback to reflection
    }
    return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));

}

From source file:com.aistor.common.utils.excel.ImportExcel.java

/**
 * ??// w w  w. j a  v a2  s  . co  m
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);
        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                if (StringUtils.isNotBlank(ef.dictType())) {
                    val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                    //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+colunm+"] " + valType);
                try {
                    if (valType == String.class) {
                        val = String.valueOf(val.toString());
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.ourlife.dev.common.utils.excel.ImportExcel.java

/**
 * ??//from   w ww.j a v a  2 s.  c o  m
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);
        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                if (StringUtils.isNotBlank(ef.dictType())) {
                    val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                    //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        val = String.valueOf(val.toString());
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.vilt.minium.impl.BaseWebElementsImpl.java

public Object invoke(Method method, Object... args) {
    if (method.isVarArgs()) {
        args = expandVarArgs(args);//from  ww  w  .j a va 2 s. c om
    }
    String expression = computeExpression(this, isAsyncMethod(method), method.getName(), args);

    if (method.getReturnType() != Object.class && method.getReturnType().isAssignableFrom(this.getClass())) {
        T webElements = WebElementsFactoryHelper.createExpressionWebElements(factory, myself, expression);
        return webElements;
    } else {
        Object result = null;

        boolean async = isAsyncMethod(method);

        Iterable<WebElementsDriver<T>> webDrivers = candidateWebDrivers();

        if (method.getReturnType() == Void.TYPE) {
            for (WebElementsDriver<T> wd : webDrivers) {
                factory.getInvoker().invokeExpression(wd, async, expression);
            }
        } else {
            if (Iterables.size(webDrivers) == 0) {
                throw new WebElementsException("The expression has no frame or window to be evaluated to");
            } else if (Iterables.size(webDrivers) == 1) {
                WebElementsDriver<T> wd = Iterables.get(webDrivers, 0);
                result = factory.getInvoker().invokeExpression(wd, async, expression);
            } else {
                String sizeExpression = computeExpression(this, false, "size");
                WebElementsDriver<T> webDriverWithResults = null;

                for (WebElementsDriver<T> wd : webDrivers) {
                    long size = (Long) factory.getInvoker().invokeExpression(wd, async, sizeExpression);
                    if (size > 0) {
                        if (webDriverWithResults == null) {
                            webDriverWithResults = wd;
                        } else {
                            throw new WebElementsException(
                                    "Several frames or windows match the same expression, so value cannot be computed");
                        }
                    }
                }

                if (webDriverWithResults != null) {
                    result = factory.getInvoker().invokeExpression(webDriverWithResults, async, expression);
                }
            }
        }

        if (logger.isDebugEnabled()) {
            String val;
            if (method.getReturnType() == Void.TYPE) {
                val = "void";
            } else {
                val = StringUtils.abbreviate(argToStringFunction.apply(result), 40);
                if (val.startsWith("'") && !val.endsWith("'"))
                    val += "(...)'";
            }
            logger.debug("[Value: {}] {}", argToStringFunction.apply(result), expression);
        }

        // let's handle numbers when return type is int
        if (method.getReturnType() == Integer.TYPE) {
            return result == null ? 0 : ((Number) result).intValue();
        } else {
            return result;
        }
    }
}

From source file:com.ancientprogramming.fixedformat4j.format.impl.FixedFormatManagerImpl.java

private <T> void readFieldData(Class<T> fixedFormatRecordClass, String data, HashMap<String, Object> foundData,
        HashMap<String, Class<?>> methodClass, Method method, String methodName, Field fieldAnnotation) {
    Object loadedData = readDataAccordingFieldAnnotation(fixedFormatRecordClass, data, method, fieldAnnotation);
    foundData.put(methodName, loadedData);
    methodClass.put(methodName, method.getReturnType());
}