List of usage examples for java.lang Class getMethods
@CallerSensitive public Method[] getMethods() throws SecurityException
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param leftSide/* ww w . ja va2 s. com*/ * @param rightSide * @param leftSideVarName * @return */ @SuppressWarnings("cast") protected String getRightSideForManyToOne(final Class<?> leftSide, final Class<?> rightSide, final String leftSideVarName) { for (Method method : rightSide.getMethods()) { String methodName = method.getName(); // Skip if it is a not a getter if (!methodName.startsWith("get")) { continue; } //System.out.println("getRightSideForManyToOne Left Class["+leftSide.getSimpleName()+"] Right["+rightSide.getSimpleName()+"] Right Side Method ["+methodName+"] Ret["+method.getReturnType().getSimpleName()+"]"); // Skip if it is a not a ManyToOne if (!method.isAnnotationPresent(javax.persistence.OneToMany.class)) { continue; } Class<?> retType = method.getReturnType(); boolean isSet = Collection.class.isAssignableFrom(retType); if (isSet) { Class<?> rt = getSetsClassType(rightSide, methodName); if (rt == null) { continue; // probably because of an interface } retType = rt; //System.out.println("Set["+(retType != null ? retType.getSimpleName() : "NULL")+"]"); } if (leftSide != retType) { continue; } javax.persistence.OneToMany oneToMany = (javax.persistence.OneToMany) method .getAnnotation(javax.persistence.OneToMany.class); String othersideName = oneToMany.mappedBy(); if (StringUtils.isNotEmpty(othersideName)) // This should never be null { //System.out.println("\nXXX["+othersideName+"]["+retType+"]"); //System.out.println("othersideName["+othersideName+"] leftSideVarName["+leftSideVarName+"]"); //System.out.println("["+leftSide.getSimpleName()+"]["+retType.getSimpleName()+"]"); if (othersideName.equals(leftSideVarName)) { return getFieldNameFromMethod(method); } } } return null; }
From source file:com.googlecode.wicketwebbeans.model.BeanMetaData.java
/** * Find action methods for a class. /*w w w . j a v a 2s . co m*/ * * @param aClass the class. * * @return an List of sorted action methods, possibly empty. */ private List<Method> getActionMethods(Class<? extends Component> aClass) { List<Method> result = new ArrayList<Method>(); for (Method method : aClass.getMethods()) { Class<?>[] params = method.getParameterTypes(); Class<?> returnType = method.getReturnType(); if (returnType.equals(Void.TYPE) && params.length == 3 && params[0] == AjaxRequestTarget.class && params[1] == Form.class && (params[2] == beanClass || params[2] == Object.class)) { result.add(method); } } Collections.sort(result, new Comparator<Method>() { public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); } }); return result; }
From source file:com.amossys.hooker.hookers.Hooker.java
protected void hookMethodsWithOutputs(final HookerListener listener, final String className, final Map<String, Integer> methods, final Map<String, Object> outputs) throws HookerInitializationException { final String hookerName = this.getHookerName(); MS.hookClassLoad(className, new MS.ClassLoadHook() { @SuppressWarnings({ "unchecked", "rawtypes" }) public void classLoaded(Class<?> resources) { /**//from ww w. j a v a 2s. co m * Based on the name of the method, we retrieve all the possibilities */ Map<GenericDeclaration, String> methodsToHook = new HashMap<GenericDeclaration, String>(); boolean found; for (String methodName : methods.keySet()) { found = false; /** * Checks if the requested method is a constructor or not */ if (className.substring(className.lastIndexOf('.') + 1).equals(methodName)) { found = true; for (int iConstructor = 0; iConstructor < resources .getConstructors().length; iConstructor++) { methodsToHook.put(resources.getConstructors()[iConstructor], methodName); } } else { for (Method m : resources.getMethods()) { if (m.getName().equals(methodName)) { found = true; methodsToHook.put(m, methodName); } } } if (!found) { SubstrateMain.log(new StringBuilder("No method found with name ").append(className) .append(":").append(methodName).toString()); } } for (final GenericDeclaration pMethod : methodsToHook.keySet()) { final String methodName = methodsToHook.get(pMethod); if (SubstrateMain.DEBUG_MODE) { SubstrateMain.log(new StringBuilder("Hooking method ").append(className).append(":") .append(methodName).toString()); } // To debug Substrate if you have a stacktrace // for (Class param : ((Method) pMethod).getParameterTypes()) { // SubstrateMain.log(" Param: " + param.getSimpleName()); // } final int intrusiveLevelFinal = methods.get(methodName); final MS.MethodPointer<Object, Object> old = new MethodPointer<Object, Object>(); MS.hookMethod_(resources, (Member) pMethod, new MS.MethodHook() { public Object invoked(final Object resources, final Object... args) throws Throwable { if (ApplicationConfig.isFiltered() || ApplicationConfig.getPackageName() == null) { return old.invoke(resources, args); } if (isSelfHooking((Member) pMethod)) { SubstrateMain.log( "Self hooking detected on method '" + ((Member) pMethod).getName() + "'."); return old.invoke(resources, args); } final String packName = ApplicationConfig.getPackageName(); final Context appContext = ApplicationConfig.getContext(); InterceptEvent event = null; if (packName != null && appContext != null) { // Open the connection to the service if not yet bound if (!serviceConnection.isBoundToTheService()) { serviceConnection.doBindService(appContext); } // Create the intercept event for this hook event = new InterceptEvent(hookerName, intrusiveLevelFinal, System.identityHashCode(resources), packName, className, methodName); //TODO: We should also save the parameters value before the call. // it requires to clone the parameters // and save them in the event if their value is different after the call /** * If specified, we execute the before method of the provided listener */ if (listener != null) { listener.before(className, pMethod, resources, event); } } /** * We invoke the original method and capture the result */ Object result = old.invoke(resources, args); // if requested we modify the output value of the invocation if (outputs != null && outputs.containsKey(methodName)) { if (result == null || outputs.get(methodName) == null || result.getClass().isAssignableFrom(outputs.get(methodName).getClass())) { result = outputs.get(methodName); } else { SubstrateMain.log("Cannot replace method " + methodName + " output with " + outputs.get(methodName) + ": types are incompatible.", false); } } // Store the result in the event (if available) if (event != null && appContext != null) { // Register the parameters of the method call in the event if (args != null) { for (Object arg : args) { if (arg != null) { String argValue = getStringRepresentationOfAttribute(arg); event.addParameter(arg.getClass().getName(), argValue); } else { event.addParameter(null, null); } } } // if the invocation returned something we store it in the event if (result != null) { String strResult = getStringRepresentationOfAttribute(result); event.setReturns(result.getClass().getName(), strResult); } else { event.setReturns(null, null); } /** * if specified, we execute the after method of the provided listener */ if (listener != null) { listener.after(className, pMethod, resources, event); } insertEvent(event, appContext); } return result; } /** * Computes if we are self hooking ourselves. To do so, we generate a stack trace to retrieve * the caller list of the current invocation and check no Hooker appears after the second entry of the stack trace. * @param pMethod * @param pMethod * @return true if we are self-hooking */ private boolean isSelfHooking(Member pMethod) { boolean selfHooking = false; StackTraceElement[] stackTrace = new Throwable().getStackTrace(); if (stackTrace.length > 2) { for (int i = 2; i < stackTrace.length; i++) { if (stackTrace[i].getClassName().startsWith(Hooker.class.getName())) { selfHooking = true; break; } } } return selfHooking; } }, old); } } }); }
From source file:plugins.PlayReader.java
protected Class<?> getSubResource(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; }/*w ww . j a v a 2 s . c o m*/ } else { type = rawType; } if (type.getAnnotation(Api.class) != null) { return type; } if (config.isScanAllResources()) { // For sub-resources that are not annotated with @Api, look for any HttpMethods. for (Method m : type.getMethods()) { if (extractOperationMethod(null, m, null) != null) { return type; } } } return null; }
From source file:io.swagger.jaxrs.Reader.java
protected Class<?> getSubResource(Method method) { final Class<?> rawType = method.getReturnType(); final Class<?> type; if (Class.class.equals(rawType)) { type = getClassArgument(method.getGenericReturnType()); if (type == null) { return null; }//ww w.j a v a 2s .c o m } else { type = rawType; } if (type.getAnnotation(Api.class) != null) { return type; } // For sub-resources that are not annotated with @Api, look for any HttpMethods. for (Method m : type.getMethods()) { if (extractOperationMethod(null, m, null) != null) { return type; } } return null; }
From source file:com.weibo.api.motan.config.AbstractInterfaceConfig.java
protected void checkInterfaceAndMethods(Class<?> interfaceClass, List<MethodConfig> methods) { if (interfaceClass == null) { throw new IllegalStateException("interface not allow null!"); }// w w w .j a v a 2s . com if (!interfaceClass.isInterface()) { throw new IllegalStateException("The interface class " + interfaceClass + " is not a interface!"); } // ?? if (methods != null && !methods.isEmpty()) { for (MethodConfig methodBean : methods) { String methodName = methodBean.getName(); if (methodName == null || methodName.length() == 0) { throw new IllegalStateException( "<motan:method> name attribute is required! Please check: <motan:service interface=\"" + interfaceClass.getName() + "\" ... ><motan:method name=\"\" ... /></<motan:referer>"); } java.lang.reflect.Method hasMethod = null; for (java.lang.reflect.Method method : interfaceClass.getMethods()) { if (method.getName().equals(methodName)) { if (methodBean.getArgumentTypes() != null && ReflectUtil.getMethodParamDesc(method).equals(methodBean.getArgumentTypes())) { hasMethod = method; break; } if (methodBean.getArgumentTypes() != null) { continue; } if (hasMethod != null) { throw new MotanFrameworkException( "The interface " + interfaceClass.getName() + " has more than one method " + methodName + " , must set argumentTypes attribute.", MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } hasMethod = method; } } if (hasMethod == null) { throw new MotanFrameworkException( "The interface " + interfaceClass.getName() + " not found method " + methodName, MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } methodBean.setArgumentTypes(ReflectUtil.getMethodParamDesc(hasMethod)); } } }
From source file:gov.nih.nci.system.web.struts.action.RestQuery.java
protected void prepareAssociations(HttpServletRequest request, Object instance, String className, String base64encodedUsernameAndPassword) throws Exception { List<String> associations = classCache.getAssociations(className); if (associations != null && associations.size() > 0) { for (int i = 0; i < associations.size(); i++) { String asscName = (String) associations.get(i); log.debug("asscName: " + asscName); String asscRole = null; String asscClass = asscName; if (asscName.indexOf("(") != -1) { asscClass = asscName.substring(asscName.indexOf("(") + 1, asscName.lastIndexOf(")")); asscRole = asscName.substring(0, asscName.indexOf("(")); }/*from w w w . ja v a 2s . c om*/ log.debug("asscClass: " + asscClass); log.debug("asscRole: " + asscRole); if (asscClass.equals("Please choose") || (asscRole == null && asscClass.equals(className))) { log.debug("Continue......."); continue; } String idName = classCache.getClassIdName(asscClass); if (idName == null || idName.trim().length() == 0) continue; String idType = classCache.getReturnType(asscClass, idName, true); Enumeration<String> parameters = request.getParameterNames(); try { String getMethodName = "get" + (asscRole.charAt(0) + "").toUpperCase() + asscRole.substring(1, asscRole.length()).trim(); log.debug("getMethodName " + getMethodName); Class classType = Class.forName(className); Method getMethod = classType.getMethod(getMethodName.trim(), null); Class returnType = getMethod.getReturnType(); log.debug("returnType " + returnType.getName()); boolean collection = false; if (returnType.getName().equals("java.util.Collection")) collection = true; while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); log.debug("parameterName: " + parameterName); log.debug("asscRole: " + asscRole); if (parameterName.startsWith(asscRole) && parameterName.indexOf("(") > 0) { String paramValue = (request.getParameter(parameterName)).trim(); if (paramValue != null && paramValue.trim().length() > 0) { Object assocObj = RESTUtil.getObject(asscClass, paramValue, request, base64encodedUsernameAndPassword, collection); log.debug("assocObj: " + assocObj); if (assocObj != null) { try { Class klass = instance.getClass(); Class type = Class.forName(asscClass); Class[] argTypes = new Class[] { type }; String methodName = "set" + (asscRole.charAt(0) + "").toUpperCase() + asscRole.substring(1, asscRole.length()); log.debug("Method name looking for: " + methodName); Method[] methods = klass.getMethods(); for (int k = 0; k < methods.length; k++) { Method method = methods[k]; log.debug("Name: " + method.getName()); Class[] types = method.getParameterTypes(); if (types != null) { if (method.getName().trim().equals(methodName.trim())) { log.debug("Instance: " + instance); log.debug("assocObj: " + assocObj.getClass().getName()); log.debug("returnType.cast(assocObj): " + returnType.cast(assocObj)); method.invoke(instance, assocObj); break; } } } break; } catch (Exception ex) { ex.printStackTrace(); throw ex; } } else { throw new Exception("Invalid id: " + paramValue + " for Class: " + className); } } } } } catch (Exception e) { e.printStackTrace(); throw e; } } } }
From source file:edu.ku.brc.specify.tools.datamodelgenerator.DatamodelGenerator.java
/** * @param leftSide//www . j av a 2 s .co m * @param rightSide * @param mappedByName * @return */ @SuppressWarnings("cast") protected String getRightSideForOneToOne(final Class<?> leftSide, final Class<?> rightSide, final String leftSideVarName, @SuppressWarnings("unused") final String mappedName, final boolean isMappedBy) { for (Method method : rightSide.getMethods()) { String methodName = method.getName(); // Skip if it is a not a getter if (!methodName.startsWith("get")) { continue; } //System.out.println("Left Class["+leftSide.getSimpleName()+"] Right["+rightSide.getSimpleName()+"] Right Side Method ["+methodName+"] Ret["+method.getReturnType().getSimpleName()+"]"); // Skip if it is a not a OneToOne if (!method.isAnnotationPresent(javax.persistence.OneToOne.class)) { continue; } Class<?> retType = method.getReturnType(); boolean isSet = Collection.class.isAssignableFrom(retType); if (isSet) { Class<?> rt = getSetsClassType(rightSide, methodName); if (rt == null) { continue; // probably because of an interface } retType = rt; //System.out.println("Set["+(retType != null ? retType.getSimpleName() : "NULL")+"]"); } String othersideName = ""; if (isMappedBy) { othersideName = getFieldNameFromMethod(method); } else { javax.persistence.OneToOne oneToOne = (javax.persistence.OneToOne) method .getAnnotation(javax.persistence.OneToOne.class); // Caller wasn't mappedBy so look for mapped By othersideName = oneToOne.mappedBy(); } if (StringUtils.isNotEmpty(othersideName) && leftSideVarName.equals(othersideName)) { return getFieldNameFromMethod(method); } } return null; }
From source file:javadz.beanutils.MethodUtils.java
/** * <p>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.//from www. j a v a 2 s . c om * In other words, it finds a method with the given name * that will take the parameters given.<p> * * <p>This method is slightly undeterminstic 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(Class clazz, String methodName, Class[] parameterTypes) { // trace logging Log log = LogFactory.getLog(MethodUtils.class); if (log.isTraceEnabled()) { log.trace("Matching name=" + methodName + " on " + clazz); } 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 (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods int paramSize = parameterTypes.length; Method bestMatch = null; Method[] methods = clazz.getMethods(); float bestMatchCost = Float.MAX_VALUE; float myCost = Float.MAX_VALUE; for (int i = 0, size = methods.length; i < size; i++) { if (methods[i].getName().equals(methodName)) { // log some trace information if (log.isTraceEnabled()) { log.trace("Found matching name:"); log.trace(methods[i]); } // compare parameters Class[] methodsParams = methods[i].getParameterTypes(); 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 Method method = getAccessibleMethod(clazz, methods[i]); if (method != null) { if (log.isTraceEnabled()) { log.trace(method + " accessible version of " + methods[i]); } 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.doitnext.jsonschema.generator.SchemaGen.java
private static boolean handleProperties(Class<?> classz, StringBuilder sb, Map<String, String> declarations, String uriPrefix) {/*from w ww.ja va 2 s . c om*/ boolean result = false; String prepend = ""; Set<String> processedFields = new HashSet<String>(); sb.append("{"); for (Field field : classz.getFields()) { JsonSchemaProperty propertyDecl = field.getAnnotation(JsonSchemaProperty.class); if (propertyDecl != null) { Class<?> propClassz = field.getType(); StringBuilder sb2 = new StringBuilder(); boolean inline = true; sb2.append("{"); if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) { if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) { inline = false; } } sb2.append("}"); if (inline) { sb.append(prepend); sb.append("\""); sb.append(propertyDecl.name()); sb.append("\":"); sb.append(sb2.toString()); prepend = ", "; } else { String id = null; JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class); if (jsc != null) id = jsc.id(); else id = propClassz.getName(); declarations.put(id, sb2.toString()); sb.append(prepend); sb.append("\""); sb.append(propertyDecl.name()); sb.append("\":{\"$ref\":\""); if (!StringUtils.isEmpty(uriPrefix)) sb.append(uriPrefix); sb.append(id); sb.append("\"}"); prepend = ", "; } processedFields.add(propertyDecl.name()); } } for (Method method : classz.getMethods()) { JsonSchemaProperty propertyDecl = method.getAnnotation(JsonSchemaProperty.class); if (propertyDecl != null && !processedFields.contains(propertyDecl.name())) { Class<?> propClassz = method.getReturnType(); StringBuilder sb2 = new StringBuilder(); boolean inline = true; sb2.append("{"); if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) { if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) { inline = false; } } sb2.append("}"); if (inline) { sb.append(prepend); sb.append("\""); sb.append(propertyDecl.name()); sb.append("\":"); sb.append(sb2.toString()); prepend = ", "; } else { String id = null; JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class); if (jsc != null) id = jsc.id(); else id = propClassz.getName(); declarations.put(id, sb2.toString()); sb.append(prepend); sb.append("\""); sb.append(propertyDecl.name()); sb.append("\":{\"$ref\":\""); if (!StringUtils.isEmpty(uriPrefix)) sb.append(uriPrefix); sb.append(id); sb.append("\"}"); prepend = ", "; } processedFields.add(propertyDecl.name()); } } sb.append("}"); return result; }