List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:com.github.wshackle.java4cpp.J4CppMain.java
private static boolean addGetterMethod(Field f, Class clss, List<Class> classes) { if (!Modifier.isPublic(f.getModifiers())) { return false; }/*from www . j av a 2s . c o m*/ if (!f.getType().isPrimitive() && !String.class.equals(f.getType()) && !classes.contains(f.getType())) { return false; } Method ma[] = clss.getMethods(); for (int i = 0; i < ma.length; i++) { Method method = ma[i]; if (method.getName().equalsIgnoreCase(f.getName())) { return false; } if (method.getName().equalsIgnoreCase("get" + f.getName())) { return false; } if (method.getName().equalsIgnoreCase("set" + f.getName())) { return false; } } return true; }
From source file:eu.qualityontime.commons.MethodUtils.java
/** * <p>/*from w w w . j a v a 2s.c om*/ * Find an accessible method that matches the given name and has compatible * parameters. Compatible parameters mean that every method parameter is * assignable from the given parameters. In other words, it finds a method * with the given name that will take the parameters given. * </p> * * <p> * This method is slightly undeterministic since it loops through methods * names and return the first matching method. * </p> * * <p> * This method is used by * {@link #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}. * * <p> * This method can match primitive parameter by passing in wrapper classes. * For example, a <code>Boolean</code> will match a primitive * <code>boolean</code> parameter. * * @param clazz * find method in this class * @param methodName * find method with this name * @param parameterTypes * find method with compatible parameters * @return The accessible method */ public static Method getMatchingAccessibleMethod(final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes) { // trace logging final Log log = LogFactory.getLog(MethodUtils.class); if (log.isTraceEnabled()) { log.trace("Matching name=" + methodName + " on " + clazz); } final MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false); // see if we can find the method directly // most of the time this works and it's much faster try { // Check the cache first Method method = getCachedMethod(md); if (method != null) { return method; } method = clazz.getMethod(methodName, parameterTypes); if (log.isTraceEnabled()) { log.trace("Found straight match: " + method); log.trace("isPublic:" + Modifier.isPublic(method.getModifiers())); } setMethodAccessible(method); // Default access superclass workaround cacheMethod(md, method); return method; } catch (final NoSuchMethodException e) { /* SWALLOW */ } // search through all methods final int paramSize = parameterTypes.length; Method bestMatch = null; final Method[] methods = clazz.getMethods(); float bestMatchCost = Float.MAX_VALUE; float myCost = Float.MAX_VALUE; for (final Method method2 : methods) { if (method2.getName().equals(methodName)) { // log some trace information if (log.isTraceEnabled()) { log.trace("Found matching name:"); log.trace(method2); } // compare parameters final Class<?>[] methodsParams = method2.getParameterTypes(); final int methodParamSize = methodsParams.length; if (methodParamSize == paramSize) { boolean match = true; for (int n = 0; n < methodParamSize; n++) { if (log.isTraceEnabled()) { log.trace("Param=" + parameterTypes[n].getName()); log.trace("Method=" + methodsParams[n].getName()); } if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) { if (log.isTraceEnabled()) { log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]); } match = false; break; } } if (match) { // get accessible version of method final Method method = getAccessibleMethod(clazz, method2); if (method != null) { if (log.isTraceEnabled()) { log.trace(method + " accessible version of " + method2); } setMethodAccessible(method); // Default access // superclass // workaround myCost = getTotalTransformationCost(parameterTypes, method.getParameterTypes()); if (myCost < bestMatchCost) { bestMatch = method; bestMatchCost = myCost; } } log.trace("Couldn't find accessible method."); } } } } if (bestMatch != null) { cacheMethod(md, bestMatch); } else { // didn't find a match log.trace("No match found."); } return bestMatch; }
From source file:com.strider.datadefender.DatabaseAnonymizer.java
/** * Calls the anonymization function for the given Column, and returns its * anonymized value.//from w ww.ja v a2 s .co m * * @param dbConn * @param row * @param column * @return * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ private Object callAnonymizingFunctionWithParameters(final Connection dbConn, final ResultSet row, final Column column, final String vendor) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final String function = column.getFunction(); if (function == null || function.equals("")) { log.warn("Function is not defined for column [" + column + "]. Moving to the next column."); return ""; } try { final String className = Utils.getClassName(function); final String methodName = Utils.getMethodName(function); final Class<?> clazz = Class.forName(className); final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance(); instance.setDatabaseConnection(dbConn); instance.setVendor(vendor); final List<Parameter> parms = column.getParameters(); final Map<String, Object> paramValues = new HashMap<>(parms.size()); final String columnValue = row.getString(column.getName()); for (final Parameter param : parms) { if (param.getValue().equals("@@value@@")) { paramValues.put(param.getName(), columnValue); } else if (param.getValue().equals("@@row@@") && param.getType().equals("java.sql.ResultSet")) { paramValues.put(param.getName(), row); } else { paramValues.put(param.getName(), param.getTypeValue()); } } final List<Object> fnArguments = new ArrayList<>(parms.size()); final Method[] methods = clazz.getMethods(); Method selectedMethod = null; methodLoop: for (final Method m : methods) { if (m.getName().equals(methodName) && m.getReturnType() == String.class) { log.debug(" Found method: " + m.getName()); log.debug(" Match w/: " + paramValues); final java.lang.reflect.Parameter[] mParams = m.getParameters(); fnArguments.clear(); for (final java.lang.reflect.Parameter par : mParams) { //log.debug(" Name present? " + par.isNamePresent()); // Note: requires -parameter compiler flag log.debug(" Real param: " + par.getName()); if (!paramValues.containsKey(par.getName())) { continue methodLoop; } final Object value = paramValues.get(par.getName()); Class<?> fnParamType = par.getType(); final Class<?> confParamType = (value == null) ? fnParamType : value.getClass(); if (fnParamType.isPrimitive() && value == null) { continue methodLoop; } if (ClassUtils.isPrimitiveWrapper(confParamType)) { if (!ClassUtils.isPrimitiveOrWrapper(fnParamType)) { continue methodLoop; } fnParamType = ClassUtils.primitiveToWrapper(fnParamType); } if (!fnParamType.equals(confParamType)) { continue methodLoop; } fnArguments.add(value); } // actual parameters check less than xml defined parameters size, because values could be auto-assigned (like 'values' and 'row' params) if (fnArguments.size() != mParams.length || fnArguments.size() < paramValues.size()) { continue; } selectedMethod = m; break; } } if (selectedMethod == null) { final StringBuilder s = new StringBuilder("Anonymization method: "); s.append(methodName).append(" with parameters matching ("); String comma = ""; for (final Parameter p : parms) { s.append(comma).append(p.getType()).append(' ').append(p.getName()); comma = ", "; } s.append(") was not found in class ").append(className); throw new NoSuchMethodException(s.toString()); } log.debug("Anonymizing function: " + methodName + " with parameters: " + Arrays.toString(fnArguments.toArray())); final Object anonymizedValue = selectedMethod.invoke(instance, fnArguments.toArray()); if (anonymizedValue == null) { return null; } return anonymizedValue.toString(); } catch (InstantiationException | ClassNotFoundException ex) { log.error(ex.toString()); } return ""; }
From source file:com.jskaleel.xml.JSONObject.java
private void populateMap(Object bean) { Class klass = bean.getClass(); // If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try {/*from w ww. java2 s.co m*/ Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { key = ""; } else { key = name.substring(3); } } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[]) null); if (result != null) { this.map.put(key, wrap(result)); } } } } catch (Exception ignore) { } } }
From source file:com.springframework.beans.GenericTypeAwarePropertyDescriptor.java
public GenericTypeAwarePropertyDescriptor(Class<?> beanClass, String propertyName, Method readMethod, Method writeMethod, Class<?> propertyEditorClass) throws IntrospectionException { super(propertyName, null, null); if (beanClass == null) { throw new IntrospectionException("Bean class must not be null"); }/*from w w w .jav a 2s . c o m*/ this.beanClass = beanClass; Method readMethodToUse = BridgeMethodResolver.findBridgedMethod(readMethod); Method writeMethodToUse = BridgeMethodResolver.findBridgedMethod(writeMethod); if (writeMethodToUse == null && readMethodToUse != null) { // Fallback: Original JavaBeans introspection might not have found matching setter // method due to lack of bridge method resolution, in case of the getter using a // covariant return type whereas the setter is defined for the concrete property type. Method candidate = ClassUtils.getMethodIfAvailable(this.beanClass, "set" + StringUtils.capitalize(getName()), (Class<?>[]) null); if (candidate != null && candidate.getParameterTypes().length == 1) { writeMethodToUse = candidate; } } this.readMethod = readMethodToUse; this.writeMethod = writeMethodToUse; if (this.writeMethod != null) { if (this.readMethod == null) { // Write method not matched against read method: potentially ambiguous through // several overloaded variants, in which case an arbitrary winner has been chosen // by the JDK's JavaBeans Introspector... Set<Method> ambiguousCandidates = new HashSet<Method>(); for (Method method : beanClass.getMethods()) { if (method.getName().equals(writeMethodToUse.getName()) && !method.equals(writeMethodToUse) && !method.isBridge()) { ambiguousCandidates.add(method); } } if (!ambiguousCandidates.isEmpty()) { this.ambiguousWriteMethods = ambiguousCandidates; } } this.writeMethodParameter = new MethodParameter(this.writeMethod, 0); GenericTypeResolver.resolveParameterType(this.writeMethodParameter, this.beanClass); } if (this.readMethod != null) { this.propertyType = GenericTypeResolver.resolveReturnType(this.readMethod, this.beanClass); } else if (this.writeMethodParameter != null) { this.propertyType = this.writeMethodParameter.getParameterType(); } this.propertyEditorClass = propertyEditorClass; }
From source file:com.opensymphony.xwork2.conversion.impl.XWorkConverter.java
/** * Looks for converter mappings for the specified class and adds it to an existing map. Only new converters are * added. If a converter is defined on a key that already exists, the converter is ignored. * * @param mapping an existing map to add new converter mappings to * @param clazz class to look for converter mappings for *//*from w w w. j ava 2 s. com*/ protected void addConverterMapping(Map<String, Object> mapping, Class clazz) { // Process <clazz>-conversion.properties file String converterFilename = buildConverterFilename(clazz); fileProcessor.process(mapping, clazz, converterFilename); // Process annotations Annotation[] annotations = clazz.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof Conversion) { Conversion conversion = (Conversion) annotation; for (TypeConversion tc : conversion.conversions()) { if (mapping.containsKey(tc.key())) { break; } if (LOG.isDebugEnabled()) { if (StringUtils.isEmpty(tc.key())) { LOG.debug("WARNING! key of @TypeConversion [#0] applied to [#1] is empty!", tc.converter(), clazz.getName()); } else { LOG.debug("TypeConversion [#0] with key: [#1]", tc.converter(), tc.key()); } } annotationProcessor.process(mapping, tc, tc.key()); } } } // Process annotated methods for (Method method : clazz.getMethods()) { annotations = method.getAnnotations(); for (Annotation annotation : annotations) { if (annotation instanceof TypeConversion) { TypeConversion tc = (TypeConversion) annotation; if (mapping.containsKey(tc.key())) { break; } String key = tc.key(); // Default to the property name if (StringUtils.isEmpty(key)) { key = AnnotationUtils.resolvePropertyName(method); if (LOG.isDebugEnabled()) { LOG.debug("Retrieved key [#0] from method name [#1]", key, method.getName()); } } annotationProcessor.process(mapping, tc, key); } } } }
From source file:eu.qualityontime.commons.DefaultBeanIntrospector.java
/** * This method fixes an issue where IndexedPropertyDescriptor behaves * differently in different versions of the JDK for 'indexed' properties * which use java.util.List (rather than an array). It implements a * workaround for Bug 28358. If you have a Bean with the following * getters/setters for an indexed property: * * <pre>//from w w w . ja va 2 s.c o m * public List getFoo() * public Object getFoo(int index) * public void setFoo(List foo) * public void setFoo(int index, Object foo) * </pre> * * then the IndexedPropertyDescriptor's getReadMethod() and getWriteMethod() * behave as follows: * <ul> * <li>JDK 1.3.1_04: returns valid Method objects from these methods.</li> * <li>JDK 1.4.2_05: returns null from these methods.</li> * </ul> * * @param beanClass * the current class to be inspected * @param descriptors * the array with property descriptors */ private void handleIndexedPropertyDescriptors(final Class<?> beanClass, final PropertyDescriptor[] descriptors) { for (final PropertyDescriptor pd : descriptors) { if (pd instanceof IndexedPropertyDescriptor) { final IndexedPropertyDescriptor descriptor = (IndexedPropertyDescriptor) pd; final String propName = descriptor.getName().substring(0, 1).toUpperCase() + descriptor.getName().substring(1); if (descriptor.getReadMethod() == null) { final String methodName = descriptor.getIndexedReadMethod() != null ? descriptor.getIndexedReadMethod().getName() : "get" + propName; final Method readMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName, EMPTY_CLASS_PARAMETERS); if (readMethod != null) { try { descriptor.setReadMethod(readMethod); } catch (final Exception e) { log.error("Error setting indexed property read method", e); } } } if (descriptor.getWriteMethod() == null) { final String methodName = descriptor.getIndexedWriteMethod() != null ? descriptor.getIndexedWriteMethod().getName() : "set" + propName; Method writeMethod = MethodUtils.getMatchingAccessibleMethod(beanClass, methodName, LIST_CLASS_PARAMETER); if (writeMethod == null) { for (final Method m : beanClass.getMethods()) { if (m.getName().equals(methodName)) { final Class<?>[] parameterTypes = m.getParameterTypes(); if (parameterTypes.length == 1 && List.class.isAssignableFrom(parameterTypes[0])) { writeMethod = m; break; } } } } if (writeMethod != null) { try { descriptor.setWriteMethod(writeMethod); } catch (final Exception e) { log.error("Error setting indexed property write method", e); } } } } } }
From source file:com.github.wshackle.java4cpp.J4CppMain.java
private static boolean addSetterMethod(Field f, Class clss, List<Class> classes) { if (!Modifier.isPublic(f.getModifiers())) { return false; }/*from w w w . j ava 2 s. c o m*/ if (!f.getType().isPrimitive() && !String.class.equals(f.getType()) && !classes.contains(f.getType())) { return false; } if (Modifier.isFinal(f.getModifiers())) { return false; } Method ma[] = clss.getMethods(); for (int i = 0; i < ma.length; i++) { Method method = ma[i]; if (method.getName().equalsIgnoreCase(f.getName())) { return false; } if (method.getName().equalsIgnoreCase("get" + f.getName())) { return false; } if (method.getName().equalsIgnoreCase("set" + f.getName())) { return false; } } return true; }
From source file:jp.go.nict.langrid.servicecontainer.handler.jsonrpc.servlet.JsonRpcServlet.java
/** * /* w w w .j ava 2s . com*/ * */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServiceContext sc = new ServletConfigServiceContext(getServletConfig()); HttpServletRequestParameterContext param = new HttpServletRequestParameterContext(req); if (param.getValue("sample") == null && param.getValue("method") != null && getMethodEnabled) { doProcess(req, resp); return; } ServiceLoader loader = new ServiceLoader(sc, defaultLoaders); String sample = param.getValue("sample"); if (sample != null) { resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); PrintWriter os = resp.getWriter(); String serviceName = getServiceName(req); String method = req.getParameter("method"); os.println("request:"); printSampleRequest(loader, serviceName, method, os); os.println(""); os.println(""); os.println("response:"); printSampleResponse(loader, serviceName, method, os); os.flush(); return; } String uri = req.getRequestURI(); String cp = getServletContext().getContextPath(); int idx = uri.indexOf(cp); if (idx == -1) { super.doGet(req, resp); return; } int sidx = uri.indexOf('/', idx + cp.length() + 1); if (sidx != -1) { resp.sendRedirect(uri.substring(idx, sidx)); return; } resp.setContentType("text/html"); resp.setCharacterEncoding("UTF-8"); PrintWriter w = resp.getWriter(); w.println("<html><head>"); w.println(css); w.println(js); w.println("</head><body>"); w.println("<h2>And now... Some JsonRpc Services</h2>"); w.println("<ul>"); ClassLoader cl = Thread.currentThread().getContextClassLoader(); Set<String> names = new TreeSet<String>(); try { for (String s : loader.listServiceNames()) { names.add(s); } int id = 0; for (String s : names) { w.print("<li><b>" + s); ServiceFactory f = loader.loadServiceFactory(cl, s); if (f == null) { w.println("<font color=\"red\">(Failed to load service factory(null))</font></b></li>"); continue; } Object service = f.getService(); if (service instanceof StreamingNotifier) { w.print("(Streaming ready!)"); } String sdesc = RpcAnnotationUtil.getServiceDescriptions(Service.class, "en"); if (sdesc != null && sdesc.length() > 0) { w.print(" - " + StringEscapeUtils.escapeHtml(sdesc)); } w.print("</b><ul>"); w.print("<li>interfaces<ul>"); try { Set<Class<?>> visited = new HashSet<Class<?>>(); for (Class<?> intf : f.getInterfaces()) { if (visited.contains(intf)) continue; visited.add(intf); if (StreamingNotifier.class.isAssignableFrom(intf)) continue; w.print("<li>" + prettyName(intf)); String desc = RpcAnnotationUtil.getServiceDescriptions(intf, "en"); if (desc != null && desc.length() > 0) { w.print(" - " + StringEscapeUtils.escapeHtml(desc)); } w.print("<ul>"); try { Set<Method> methods = new TreeSet<Method>(new Comparator<Method>() { public int compare(Method o1, Method o2) { int r = o1.getName().compareTo(o2.getName()); if (r != 0) return r; return o1.getParameterTypes().length - o2.getParameterTypes().length; } }); methods.addAll(Arrays.asList(intf.getMethods())); for (Method m : methods) { if (m.isSynthetic()) continue; if ((m.getModifiers() & Modifier.PUBLIC) == 0) continue; printMethod(s, m, getImplementedMethod(service, m), id++, w); } } finally { w.println("</ul></li>"); } } } catch (SecurityException e) { } finally { w.println("</ul></li>"); } w.print("<li>implementation<ul>"); if (service != null) { w.println("<li>" + prettyName(service.getClass()) + "</li>"); if (service instanceof AbstractCompositeService) { boolean first = true; for (Pair<Invocation, Class<?>> v : ((AbstractCompositeService) service).invocations()) { if (first) { w.println("<li>invocations<ul>"); first = false; } w.println( "<li><b>" + v.getFirst().name() + (v.getFirst().required() ? "(required)" : "") + "</b>: " + prettyName(v.getSecond()) + "</li>"); } if (!first) { w.println("</ul></li>"); } } } else { w.println("<li><font color=\"red\"><b>failed to load implementation class.</b></font></li>"); } w.println("</ul></li>"); w.println("</ul></li>"); w.println("<br/>"); } } catch (IOException e) { w.println("<pre><font color=\"red\">"); e.printStackTrace(w); w.println("</font></pre>"); } w.println("</ul>"); w.println("</body></html>"); }
From source file:com.newmainsoftech.spray.slingong.datastore.Slim3AnnotationTransactionAspectPointcutTest.java
@SuppressWarnings("unused") @Test// ww w . j a v a 2 s . co m public void test_GlobalTransaction_class() throws Throwable { final String globalTransactionClassKnownName = "org.slim3.datastore.GlobalTransaction"; final Class<GlobalTransaction> globalTransactionClass = GlobalTransaction.class; Assert.assertEquals( String.format( "Pointcut expressions in %1$s class MAY need update regarding %2$s class " + "refactoring from %3$s to %4$s.", Slim3AnnotationTransactionAspect.class.getName(), globalTransactionClass.getSimpleName(), globalTransactionClassKnownName, globalTransactionClass.getName()), globalTransactionClassKnownName, globalTransactionClass.getName()); String methodName = "commit"; try { Method method = globalTransactionClass.getMethod(methodName, (Class<?>[]) null); } catch (NoSuchMethodException exception) { Assert.fail(String.format( "Pointcut expressions in %1$s class MAY need update because " + "%2$s method is not found among public methods of %3$s any longer.", Slim3AnnotationTransactionAspect.class.getName(), methodName, globalTransactionClass.toString())); } methodName = "rollback"; try { Method method = globalTransactionClass.getMethod(methodName, (Class<?>[]) null); } catch (NoSuchMethodException exception) { Assert.fail(String.format( "Pointcut expressions in %1$s class MAY need update because " + "%2$s method is not found among public methods of %3$s any longer.", Slim3AnnotationTransactionAspect.class.getName(), methodName, globalTransactionClass.toString())); } int putMethodCount = 0; int deleteMethodCount = 0; Method[] methodArrays = globalTransactionClass.getMethods(); for (Method method : methodArrays) { if ("put".equals(method.getName())) { putMethodCount++; } else if (method.getName().startsWith("delete")) { deleteMethodCount++; } } // for Assert.assertTrue( String.format( "Pointcut expressions in %1$s class MAY need update because " + "%2$s method is not found among public methods of %3$s any longer.", Slim3AnnotationTransactionAspect.class.getName(), "put", globalTransactionClass.toString()), (putMethodCount > 0)); Assert.assertTrue(String.format( "Pointcut expressions in %1$s class MAY need update because " + "%2$s method is not found among public methods of %3$s any longer.", Slim3AnnotationTransactionAspect.class.getName(), "delete", globalTransactionClass.toString()), (deleteMethodCount > 0)); }