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.lcw.one.common.utils.excel.ImportExcel.java

/**
 * ??//  w w w.j a v a 2s.  c  om
 * @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) {
                        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.coul.common.excel.ImportExcel.java

/**
 * ??//  w  w w  . ja va 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) {
                        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.evolveum.midpoint.repo.sql.query2.definition.ClassDefinitionParser.java

private JpaLinkDefinition parseMethod(Method method) {
    CollectionSpecification collectionSpecification; // non-null if return type is Set<X>, null if it's X
    Type returnedContentType; // X in return type, which is either X or Set<X>
    if (Set.class.isAssignableFrom(method.getReturnType())) {
        // e.g. Set<RObject> or Set<String> or Set<REmbeddedReference<RFocus>>
        Type returnType = method.getGenericReturnType();
        if (!(returnType instanceof ParameterizedType)) {
            throw new IllegalStateException("Method " + method + " returns a non-parameterized collection");
        }/*from   w  w  w  . j a v  a 2s.  c o m*/
        returnedContentType = ((ParameterizedType) returnType).getActualTypeArguments()[0];
        collectionSpecification = new CollectionSpecification();
    } else {
        returnedContentType = method.getReturnType();
        collectionSpecification = null;
    }

    ItemPath itemPath = getJaxbName(method);
    String jpaName = getJpaName(method);
    Class jpaClass = getClass(returnedContentType);

    // sanity check
    if (Set.class.isAssignableFrom(jpaClass)) {
        throw new IllegalStateException("Collection within collection is not supported: method=" + method);
    }

    JpaLinkDefinition<? extends JpaDataNodeDefinition> linkDefinition;
    Any any = method.getAnnotation(Any.class);
    if (any != null) {
        JpaAnyContainerDefinition targetDefinition = new JpaAnyContainerDefinition(jpaClass);
        QName jaxbNameForAny = new QName(any.jaxbNameNamespace(), any.jaxbNameLocalPart());
        linkDefinition = new JpaLinkDefinition<>(jaxbNameForAny, jpaName, collectionSpecification, false,
                targetDefinition);
    } else if (ObjectReference.class.isAssignableFrom(jpaClass)) {
        boolean embedded = method.isAnnotationPresent(Embedded.class);
        // computing referenced entity type from returned content type like RObjectReference<RFocus> or REmbeddedReference<RRole>
        Class referencedJpaClass;
        if (returnedContentType instanceof ParameterizedType) {
            referencedJpaClass = getClass(
                    ((ParameterizedType) returnedContentType).getActualTypeArguments()[0]);
        } else {
            referencedJpaClass = RObject.class;
        }
        JpaReferenceDefinition targetDefinition = new JpaReferenceDefinition(jpaClass, referencedJpaClass);
        linkDefinition = new JpaLinkDefinition<>(itemPath, jpaName, collectionSpecification, embedded,
                targetDefinition);
    } else if (isEntity(jpaClass)) {
        JpaEntityDefinition content = parseClass(jpaClass);
        boolean embedded = method.isAnnotationPresent(Embedded.class)
                || jpaClass.isAnnotationPresent(Embeddable.class);
        linkDefinition = new JpaLinkDefinition<JpaDataNodeDefinition>(itemPath, jpaName,
                collectionSpecification, embedded, content);
    } else {
        boolean lob = method.isAnnotationPresent(Lob.class);
        boolean enumerated = method.isAnnotationPresent(Enumerated.class);
        //todo implement also lookup for @Table indexes
        boolean indexed = method.isAnnotationPresent(Index.class);
        Class jaxbClass = getJaxbClass(method, jpaClass);

        if (method.isAnnotationPresent(IdQueryProperty.class)) {
            if (collectionSpecification != null) {
                throw new IllegalStateException(
                        "ID property is not allowed to be multivalued; for method " + method);
            }
            itemPath = new ItemPath(new IdentifierPathSegment());
        } else if (method.isAnnotationPresent(OwnerIdGetter.class)) {
            if (collectionSpecification != null) {
                throw new IllegalStateException(
                        "Owner ID property is not allowed to be multivalued; for method " + method);
            }
            itemPath = new ItemPath(new ParentPathSegment(), new IdentifierPathSegment());
        }

        JpaPropertyDefinition propertyDefinition = new JpaPropertyDefinition(jpaClass, jaxbClass, lob,
                enumerated, indexed);
        // Note that properties are considered to be embedded
        linkDefinition = new JpaLinkDefinition<JpaDataNodeDefinition>(itemPath, jpaName,
                collectionSpecification, true, propertyDefinition);
    }
    return linkDefinition;
}

From source file:com.dungnv.vfw5.base.service.BaseFWServiceImpl.java

private String buildOrder(TModel tForm, String sortType, String sortField) {
    String order = "";
    Map<String, String> lstHashMap = new HashMap<>();
    lstHashMap = buildHasMapOrder(sortType, sortField);
    if (tForm == null) {
        for (String item : lstHashMap.keySet()) {
            order = order + " , " + item + " " + lstHashMap.get(item);
        }//  w  w  w .j ava 2 s. c om

        return order.replaceFirst(",", "");
    }
    Method methodForms[] = tForm.getClass().getDeclaredMethods();

    for (String item : lstHashMap.keySet()) {
        try {
            Method methods = tForm.getClass().getMethod(DataUtil.getGetterOfColumn(item));

            String returnType = methods.getReturnType().getSimpleName().toUpperCase();
            if (ParamUtils.TYPE_NUMBER.indexOf(returnType) >= 0) {
                order = order + " , " + item + " " + lstHashMap.get(item);

            } else {
                order = order + " , " + StringUtils.formatOrder(item, lstHashMap.get(item));
            }
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(BaseFWServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SecurityException ex) {
            Logger.getLogger(BaseFWServiceImpl.class.getName()).log(Level.SEVERE, null, ex);

        }
    }
    return order.replaceFirst(",", "");
}

From source file:com.bstek.dorado.util.proxy.MethodInterceptorDispatcher.java

public Object invoke(Object object, Method method, Method procssed, Object[] args) throws Throwable {
    if (method.equals(EQUALS_METHOD)) {
        Object proxyTarget = ProxyBeanUtils.getProxyTarget(args[0]);
        if (proxyTarget == object)
            return Boolean.TRUE;
        args = new Object[] { proxyTarget };
    } else if (object instanceof Serializable && method.getName().equals(WRITE_REPLACE)
            && method.getReturnType().equals(Object.class)) {
        try {/*  ww w.  j  a v  a  2 s.co m*/
            Class<?> realClass = ProxyBeanUtils.getProxyTargetType(object);
            realClass.getMethod(WRITE_REPLACE, new Class<?>[0]);
        } catch (NoSuchMethodException e) {
            return getObjectForSerialization(object);
        }
    }

    if (subMethodInterceptors != null && filterMethod(method)) {
        MethodInterceptorChain methodInterceptorChain = new MethodInterceptorChain(subMethodInterceptors,
                createJavassistFinalMethodInterceptor(method, procssed),
                getMethodInterceptorFilter(object, method, args));

        MethodInvocation mockMethodInvocation = createMethodInvocation(object, method, args,
                methodInterceptorChain);
        MethodInterceptor methodInterceptor = methodInterceptorChain.next(mockMethodInvocation);
        return methodInterceptor.invoke(mockMethodInvocation);
    } else {
        return procssed.invoke(object, args);
    }
}

From source file:cz.cuni.mff.d3s.tools.perfdoc.server.measuring.codegen.CodeGenerator.java

private void makeAndCompileMethodCode(BenchmarkSetting setting) throws CompileException, IOException {

    MethodReflectionInfo mrInfo = (MethodReflectionInfo) setting.getTestedMethod();
    Method testedMethod = mrInfo.getMethod();

    VelocityContext context = new VelocityContext();

    context.put("mFunction", testedMethod);
    context.put("mFunctionIsStatic", Modifier.isStatic(testedMethod.getModifiers()));
    context.put("mClass", mrInfo.getContainingClass().getName());
    context.put("mFunctionIsNotVoid", !(testedMethod.getReturnType().equals(Void.TYPE)));

    writeCode(context, templateMethodName);

    String javaSourceName = javaDestinationDir + directoryName + "/" + templateMethodName + ".java";
    String javaClassDirectory = compiledClassDestinationDir + directoryName;

    List<String> classPaths = getCompilationClassPaths();
    classPaths.add(javaClassDirectory);//from  w w w  . j  a v  a  2s.c o m

    Compiler.compile(javaSourceName, classPaths);
}

From source file:com.perfect.autosdk_v4.core.JsonProxy.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String addr = service.serverUrl + AddressUtil.getJsonAddr(interfaces) + '/' + method.getName();
    log.info("Current Calling URL: " + addr);
    PrintUtil.println("Current Calling URL: " + addr);
    JsonConnection conn = new GZIPJsonConnection(addr);
    conn.setConnectTimeout(service.connectTimeoutMills);
    conn.setReadTimeout(service.readTimeoutMills);
    conn.sendRequest(makeRequest(args[0]));
    JsonEnvelop<ResHeader, ?> response = conn.readResponse(ResHeader.class, method.getReturnType());
    ResHeaderUtil.resHeader.set(response.getHeader());
    return response.getBody();
}

From source file:com.topsem.common.io.excel.ImportExcel.java

/**
 * ??/*  www. j a v  a2  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) {
                        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.fengduo.spark.commons.file.excel.ImportExcel.java

/**
 * ??//from  w  w w  .  j a  va 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) {
                        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.jaliansystems.activeMQLite.impl.ObjectRepository.java

/**
 * Invoke a method on a local object.// w ww .  j  av a  2  s.com
 * 
 * @param message
 *            the message received.
 * @param client
 *            the repository client.
 * @return the return value from the method invocation.
 * @throws Exception
 *             the exception
 */
public Object invoke(JMSLiteMessage message, RepositoryClient client) throws Exception {
    ObjectHandle handle = (ObjectHandle) message.read();
    String methodName = (String) message.read();
    Object[] args = (Object[]) message.read();

    Object object = getObject(handle);
    if (object == null)
        throw new IllegalArgumentException("Could not find local object: " + handle);
    if (client != null && args != null)
        for (int i = 0; i < args.length; i++) {
            if (args[i] != null && args[i] instanceof ObjectHandle)
                args[i] = lookupHandle((ObjectHandle) args[i], client);
        }
    Method method = findMethod(object, methodName, args);
    if (method == null)
        throw new NoSuchMethodError(
                "Could not find method: " + methodName + " on Object of type " + object.getClass().getName());
    Object rval = method.invoke(object, args);
    Class<?> rtype = method.getReturnType();
    if (rtype.isInterface() && exportedInterfaces.contains(rtype) && rval != null) {
        rval = createHandle(rval, rtype);
    }
    return rval;
}