List of usage examples for java.lang.reflect Method getReturnType
public Class<?> getReturnType()
From source file:com.gargoylesoftware.htmlunit.SimpleWebTestCase.java
/** * From Junit. Test if the method is a junit test. * @param method the method//from ww w. j ava 2 s.co m * @return <code>true</code> if this is a junit test */ private boolean isPublicTestMethod(final Method method) { return method.getParameterTypes().length == 0 && (method.getName().startsWith("test") || method.getAnnotation(Test.class) != null) && method.getReturnType() == Void.TYPE && Modifier.isPublic(method.getModifiers()); }
From source file:com.hablutzel.cmdline.CommandLineApplication.java
/** * Validate a Method to be a main command line application method. * * Methods with more than 1 argument are not allowed. Methods with return types * are not allowed. Methods that throw an exception other than * org.apache.commons.cli.CommandLineException are not allowed, * * @param method the method to validate/*from w w w. j a v a 2s .co m*/ * @return A new method helper for the method */ private CommandLineMethodHelper getHelperForCommandLineMain(Method method) throws CommandLineException { // Validate that the return type is a void if (!method.getReturnType().equals(Void.TYPE)) { throw new CommandLineException("For method " + method.getName() + ", the return type is not void"); } // Validate the exceptions throws by the method for (Class<?> clazz : method.getExceptionTypes()) { if (!clazz.equals(CommandLineException.class)) { throw new CommandLineException("For method " + method.getName() + ", there is an invalid exception class " + clazz.getName()); } } // In order to get ready to create the configuration instance, // we will need to know the command line option type // and the element type. Class<?> elementClass; MethodType methodType; Converter converter; // Get the parameters of the method. We'll use these to // determine what type of option we have - scalar, boolean, etc. Class<?> parameterClasses[] = method.getParameterTypes(); // See what the length tells us switch (parameterClasses.length) { case 0: throw new CommandLineException("Main command line method must take arguments"); case 1: { // For a method with one argument, we have to look // more closely at the argument. It has to be a simple // scalar object, an array, or a list. Class<?> parameterClass = parameterClasses[0]; if (parameterClass.isArray()) { // For an array, we get the element class based on the // underlying component type methodType = MethodType.Array; elementClass = parameterClass.getComponentType(); } else { // For a scalar, we get the element type from the // type of the parameter. methodType = MethodType.Scalar; elementClass = parameterClass.getClass(); } // Now that we have the element type, make sure it's convertable converter = ConvertUtils.lookup(String.class, elementClass); if (converter == null) { throw new CommandLineException("Cannot find a conversion from String to " + elementClass.getName() + " for method " + method.getName()); } break; } default: { // Other method types not allowed. throw new CommandLineException("Method " + method.getName() + " has too many arguments"); } } // Now we can return the configuration for this method return new CommandLineMethodHelper(method, methodType, elementClass, converter); }
From source file:net.sf.ehcache.config.BeanHandler.java
/** * Finds a setter method.//from ww w. j a v a 2 s. c o m */ private Method findSetMethod(final Class objClass, final String prefix, final String name) throws Exception { final String methodName = makeMethodName(prefix, name); final Method[] methods = objClass.getMethods(); Method candidate = null; for (int i = 0; i < methods.length; i++) { final Method method = methods[i]; if (!method.getName().equals(methodName)) { continue; } if (Modifier.isStatic(method.getModifiers())) { continue; } if (method.getParameterTypes().length != 1) { continue; } if (!method.getReturnType().equals(Void.TYPE)) { continue; } if (candidate != null) { throw new Exception("Multiple " + methodName + "() methods in class " + objClass.getName() + "."); } candidate = method; } return candidate; }
From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java
/** * ??// w w w . j av a2 s. c o m * @param cls * @param groups */ public <E> List<E> getDataList(Class<E> cls, Map<String, Object> inportInfo, int... groups) throws InstantiationException, IllegalAccessException { List<Object[]> annotationList = Lists.newArrayList(); // Get annotation field Field[] fs = cls.getDeclaredFields(); ExcelSheet esarr = cls.getAnnotation(ExcelSheet.class); String annTitle = ""; if (esarr == null) return Lists.newArrayList(); annTitle = esarr.value(); 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(); //??? if (!"".equals(annTitle)) { String title = StringUtils.trim(this.getCellValue(this.getRow(0), 0).toString()); if (!annTitle.equals(title)) { inportInfo.put("success", false); inportInfo.put("message", "??"); return 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.tealeaf.plugin.PluginEvent.java
private static String invokeMethod(Object targetObject, Object[] parameters, String methodName, String className) {//from www . j a va2 s . c o m String retStr = "{}"; if (targetObject == null) { logger.log("{plugins} WARNING: Event could not be delivered for missing plugin:", className); return retStr; } boolean found = false; for (Method method : targetObject.getClass().getMethods()) { if (!method.getName().equals(methodName)) { continue; } Class<?>[] parameterTypes = method.getParameterTypes(); boolean match = true; for (int i = 0; i < parameterTypes.length; i++) { if (parameters[i] == null) { continue; } if (!parameterTypes[i].isAssignableFrom(parameters[i].getClass())) { match = false; break; } } if (!match && parameters.length != 0) { try { // try and coerce string argument in the first place to a JSONObject if (parameters[0] instanceof String) { JSONObject arg = new JSONObject((String) parameters[0]); parameters[0] = arg; if (parameterTypes[0].isAssignableFrom(parameters[0].getClass())) { match = true; } } } catch (JSONException e) { // first param is not valid JSON. Pass. } } if (match) { try { if (method.getReturnType().equals(Void.TYPE)) { method.invoke(targetObject, parameters); } else if (method.getReturnType().equals(String.class)) { retStr = (String) method.invoke(targetObject, parameters); } else { retStr = "" + method.invoke(targetObject, parameters); } found = true; } catch (IllegalArgumentException e) { logger.log(e); } catch (IllegalAccessException e) { logger.log(e); } catch (InvocationTargetException e) { logger.log(e); } } } if (!found) { logger.log("{plugins} WARNING: Unknown event could not be delivered for plugin:", className, ", method:", methodName); } if (retStr == null) { retStr = "{}"; } return retStr; }
From source file:freemarker.ext.dump.BaseDumpDirective.java
private String getReturnTypeName(Method method) { Class<?> cls = method.getReturnType(); Package pkg = cls.getPackage(); if (pkg != null) { // void return type has null package String packageName = pkg.getName(); if (packageName.startsWith("java")) { return getSimpleTypeName(cls); }/*from w w w .j a v a 2 s . c om*/ } return cls.getName(); }
From source file:com.funtl.framework.smoke.core.commons.excel.ImportExcel.java
/** * ??/*from ww 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.netspective.sparx.form.action.ActionWrapper.java
public void locateValidator() throws NoSuchMethodException { final Method isValidMethod = getMethod(isValidMethodName, List.class) == null ? getMethod(isValidMethodName, (Class[]) null) : getMethod(isValidMethodName, List.class); if (isValidMethod != null) { if (isValidMethod.getReturnType() == boolean.class) { actionValidator = new ActionValidator() { public boolean isValid(Object instance, List messages) throws Exception { Boolean result = (Boolean) isValidMethod.invoke(instance, new Object[] { messages }); return result.booleanValue(); }//w w w. j a v a 2s.com }; } } else actionValidator = null; }
From source file:com.joint.base.util.excel.ImportExcel.java
/** * ??/*ww w . 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.jsmartframework.web.manager.BeanHelper.java
void setAuthMethods(Class<?> clazz) { if (!authMethods.containsKey(clazz)) { List<Method> methods = new ArrayList<>(); for (Method method : getBeanMethods(clazz)) { if (!method.isAnnotationPresent(AuthMethod.class)) { continue; }/*from www. ja v a 2s . c om*/ Class<?> returnType = method.getReturnType(); if (Boolean.class == returnType || boolean.class == returnType) { methods.add(method); } } authMethods.put(clazz, methods.toArray(new Method[methods.size()])); } }