List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:com.hc.wx.server.common.bytecode.ReflectUtils.java
/** * ???/*w w w . j a va 2 s . c o m*/ * * @param clazz * @param methodName ??method1(int, String)?????????method2 * @return * @throws NoSuchMethodException * @throws ClassNotFoundException * @throws IllegalStateException ??????? */ public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = clazz.getName() + "." + methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature += StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; }
From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java
private void printSampleResponse(ServiceLoader loader, String serviceName, String method, PrintWriter os) throws ServletException, IOException { ServiceFactory f = loader.loadServiceFactory(Thread.currentThread().getContextClassLoader(), serviceName); Method met = null;//from w w w . ja v a 2s. co m for (Class<?> c : f.getInterfaces()) { for (Method m : c.getMethods()) { if (m.getName().equals(method)) { met = m; break; } } if (met != null) break; } try { JsonRpcResponse jres = new JsonRpcResponse(); jres.setResult(ClassUtil.newDummyInstance(met.getReturnType())); JSON.encode(jres, os); } catch (JSONException e) { e.printStackTrace(os); } catch (InstantiationException e) { e.printStackTrace(os); } catch (IllegalAccessException e) { e.printStackTrace(os); } }
From source file:org.apache.click.extras.spring.SpringClickServlet.java
/** * Load the pageClass bean setter methods * * @param pageClass the page class/*from ww w . j a v a 2 s . c o m*/ */ private void loadSpringBeanSetterMethods(Class<? extends Page> pageClass) { Method[] methods = pageClass.getMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; String methodName = method.getName(); if (methodName.startsWith("set") && !SETTER_METHODS_IGNORE_SET.contains(methodName) && method.getParameterTypes().length == 1) { // Get the bean name from the setter method name HtmlStringBuffer buffer = new HtmlStringBuffer(); buffer.append(Character.toLowerCase(methodName.charAt(3))); buffer.append(methodName.substring(4)); String beanName = buffer.toString(); // If Spring contains the bean then cache in map list if (getApplicationContext().containsBean(beanName)) { List<BeanNameAndMethod> beanList = pageSetterBeansMap.get(pageClass); if (beanList == null) { beanList = new ArrayList<BeanNameAndMethod>(); pageSetterBeansMap.put(pageClass, beanList); } beanList.add(new BeanNameAndMethod(beanName, method)); } } } }
From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java
private void printSampleRequest(ServiceLoader loader, String serviceName, String method, PrintWriter os) throws ServletException, IOException { ServiceFactory f = loader.loadServiceFactory(Thread.currentThread().getContextClassLoader(), serviceName); Method met = null;//ww w . ja v a 2 s.c o m for (Class<?> c : f.getInterfaces()) { for (Method m : c.getMethods()) { if (m.getName().equals(method)) { met = m; break; } } if (met != null) break; } try { Class<?>[] types = met.getParameterTypes(); Object[] params = new Object[types.length]; for (int i = 0; i < types.length; i++) { params[i] = ClassUtil.newDummyInstance(types[i]); } JsonRpcRequest jreq = new JsonRpcRequest(); jreq.setMethod(method); jreq.setParams(params); JSON.encode(jreq, os); } catch (JSONException e) { e.printStackTrace(os); } catch (InstantiationException e) { e.printStackTrace(os); } catch (IllegalAccessException e) { e.printStackTrace(os); } }
From source file:sh.scrap.scrapper.functions.StringFunctionFactory.java
private Method findMethod(Class<?> targetClass, String methodName, Object mainArgument, Map<String, Object> annotations) { if (mainArgument == null) return MethodUtils.getMatchingAccessibleMethod(targetClass, methodName, String.class); else if (annotations.size() == 0) return MethodUtils.getMatchingAccessibleMethod(targetClass, methodName, String.class, mainArgument.getClass()); Method candidate = null;//from www .j av a2s . c o m for (Method method : targetClass.getMethods()) if (method.getName().equals(methodName)) { candidate = method; String[] names = discoverer.getParameterNames(method); if (names.length > 2) { annotations.put(names[1], mainArgument); List<String> paramNames = Arrays.asList(names); if (paramNames.containsAll(annotations.keySet()) && annotations.keySet().contains(paramNames)) return candidate; } else return candidate; } if (candidate == null) throw new IllegalArgumentException("Unknown function [" + methodName + "]"); return candidate; }
From source file:edu.vt.middleware.ldap.props.AbstractPropertyInvoker.java
/** * Initializes the properties map with the supplied class. * * @param c to read methods from/*from w ww . j ava 2s . co m*/ * @param domain optional domain that properties are in */ protected void initialize(final Class<?> c, final String domain) { final String cacheKey = new StringBuilder(c.getName()).append("@").append(domain).toString(); if (PROPERTIES_CACHE.containsKey(cacheKey)) { this.properties = PROPERTIES_CACHE.get(cacheKey); } else { this.properties = new HashMap<String, Method[]>(); PROPERTIES_CACHE.put(cacheKey, this.properties); for (Method method : c.getMethods()) { if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) { final String mName = method.getName().substring(3); final String pName = new StringBuilder(domain).append(mName.substring(0, 1).toLowerCase()) .append(mName.substring(1, mName.length())).toString(); if (this.properties.containsKey(pName)) { final Method[] m = this.properties.get(pName); m[1] = method; this.properties.put(pName, m); } else { this.properties.put(pName, new Method[] { null, method }); } } else if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) { final String mName = method.getName().substring(3); final String pName = new StringBuilder(domain).append(mName.substring(0, 1).toLowerCase()) .append(mName.substring(1, mName.length())).toString(); if (this.properties.containsKey(pName)) { final Method[] m = this.properties.get(pName); m[0] = method; this.properties.put(pName, m); } else { this.properties.put(pName, new Method[] { method, null }); } } else if ("initialize".equals(method.getName()) && method.getParameterTypes().length == 0) { final String pName = new StringBuilder(domain).append(method.getName()).toString(); this.properties.put(pName, new Method[] { method, method }); } } } this.clazz = c; }
From source file:gov.nih.nci.system.web.struts.action.CreateAction.java
private void setParameterValue(Class klass, Object instance, String name, String value) throws NumberFormatException, Exception { if (value != null && value.trim().length() == 0) value = null;/* ww w . j ava2s.c o m*/ try { String paramName = name.substring(0, 1).toUpperCase() + name.substring(1); Method[] allMethods = klass.getMethods(); for (Method m : allMethods) { String mname = m.getName(); if (mname.equals("get" + paramName)) { Class type = m.getReturnType(); Class[] argTypes = new Class[] { type }; Method method = null; while (klass != Object.class) { try { Method setMethod = klass.getDeclaredMethod("set" + paramName, argTypes); setMethod.setAccessible(true); Object converted = convertValue(type, value); if (converted != null) setMethod.invoke(instance, converted); break; } catch (NumberFormatException e) { throw e; } catch (NoSuchMethodException ex) { klass = klass.getSuperclass(); } catch (Exception e) { throw e; } } } } } catch (Exception e) { e.printStackTrace(); throw e; } }
From source file:io.konik.utils.RandomInvoiceGenerator.java
public Object populteData(Class<?> root, String name) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { Object rootObj;/*from w ww. j av a2s .c o m*/ if (isLeafType(root)) {//final type return generatePrimitveValue(root, name); } rootObj = createNewInstance(root); // get method and populate each of them Method[] methods = root.getMethods(); for (Method method : methods) { int methodModifiers = method.getModifiers(); Class<?> methodParameter = null; if (Modifier.isAbstract(methodModifiers) || method.isSynthetic()) continue; if (method.getName().startsWith("add")) { methodParameter = method.getParameterTypes()[0]; if (methodParameter != null && !methodParameter.isArray() && (methodParameter.isInterface() || Modifier.isAbstract(methodParameter.getModifiers()))) { continue; } } //getter else if (method.getName().startsWith("get") && !Collection.class.isAssignableFrom(method.getReturnType()) && !method.getName().equals("getClass") && !Modifier.isAbstract(methodModifiers)) { methodParameter = method.getReturnType(); } else { continue;// next on setter } if (methodParameter == null || methodParameter.isInterface()) { continue; } Object popultedData = populteData(methodParameter, method.getName()); setValue(rootObj, method, popultedData); } return rootObj; }
From source file:com.tmind.framework.pub.utils.MethodUtils.java
private static synchronized Method[] getPublicDeclaredMethods(Class clz) { // Looking up Class.getDeclaredMethods is relatively expensive, // so we cache the results. final Class fclz = clz; Method[] result = (Method[]) declaredMethodCache.get(fclz); if (result != null) { return result; }// w w w . j a v a 2 s. c o m // We have to raise privilege for getDeclaredMethods result = (Method[]) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { return fclz.getDeclaredMethods(); } catch (SecurityException ex) { // this means we're in a limited security environment // so let's try going through the public methods // and null those those that are not from the declaring // class Method[] methods = fclz.getMethods(); for (int i = 0, size = methods.length; i < size; i++) { Method method = methods[i]; if (!(fclz.equals(method.getDeclaringClass()))) { methods[i] = null; } } return methods; } } }); // Null out any non-public methods. for (int i = 0; i < result.length; i++) { Method method = result[i]; if (method != null) { int mods = method.getModifiers(); if (!Modifier.isPublic(mods)) { result[i] = null; } } } // Add it to the cache. declaredMethodCache.put(clz, result); return result; }
From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java
@SuppressWarnings("unchecked") @Override/* ww w . j av a 2s . c o m*/ public void saveSettings(Settings instance, String fn, String comment) { Class<?> clazz = instance.getClass().getInterfaces()[0]; Class<?> invocableClazz = instance.getClass(); // File file = new File("/" + DIR_PATH + "/" + fn); File file = new File(fn); Properties props = new SortedProperties(); Method[] methods = clazz.getMethods(); for (Method method : methods) { // Find setters if (method.getName().startsWith("set")) { if (method.isAnnotationPresent(Param.class)) { Annotation annotation = method.getAnnotation(Param.class); Param param = (Param) annotation; if (param.name().equals("") || param.values().length == 0) { throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName() + " with method " + method.getName()); } Class<?>[] paramClazzes = method.getParameterTypes(); if (paramClazzes.length != 1) { throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName() + " with method " + method.getName()); } // Check param belongs to List Class<?> paramClazz = paramClazzes[0]; try { if (List.class.isAssignableFrom(paramClazz)) { // Oh, its array... // May be its InetSocketAddress? Type[] gpt = method.getGenericParameterTypes(); if (gpt[0] instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) gpt[0]; Type[] typeArguments = type.getActualTypeArguments(); for (Type typeArgument : typeArguments) { Class<?> classType = ((Class<?>) typeArgument); if (InetSocketAddress.class.isAssignableFrom(classType)) { List<InetSocketAddress> isaArr = (List<InetSocketAddress>) invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance); int cnt = isaArr.size(); props.setProperty(param.name() + ".count", String.valueOf(cnt)); for (int i = 0; i < cnt; ++i) { props.setProperty(param.name() + "." + String.valueOf(i) + ".ip", isaArr.get(i).getHostString()); props.setProperty(param.name() + "." + String.valueOf(i) + ".port", String.valueOf(isaArr.get(i).getPort())); } } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implemented yet"); } } } } else if (paramClazz.isPrimitive()) { props.setProperty(param.name(), String.valueOf(invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance))); } else if (String.class.isAssignableFrom(paramClazz)) { props.setProperty(param.name(), (String) (invocableClazz .getMethod("get" + method.getName().substring(3)).invoke(instance))); } else { throw new RuntimeException("Settings param in class " + clazz.getCanonicalName() + " with method " + method.getName() + " not implemented yet"); } BotUtils.saveProperties(file, props, "Bot v" + VERSION); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | IOException e) { e.printStackTrace(); } } } } }