List of usage examples for java.lang.reflect Method getModifiers
@Override public int getModifiers()
From source file:org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory.java
private void attachTaskAction(final Method method, TaskClassInfo taskClassInfo, Collection<String> processedMethods) { if (method.getAnnotation(TaskAction.class) == null) { return;/*from w w w . j a v a 2s . co m*/ } if (Modifier.isStatic(method.getModifiers())) { throw new GradleException(String.format("Cannot use @TaskAction annotation on static method %s.%s().", method.getDeclaringClass().getSimpleName(), method.getName())); } final Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length > 1) { throw new GradleException(String.format( "Cannot use @TaskAction annotation on method %s.%s() as this method takes multiple parameters.", method.getDeclaringClass().getSimpleName(), method.getName())); } if (parameterTypes.length == 1) { if (!parameterTypes[0].equals(IncrementalTaskInputs.class)) { throw new GradleException(String.format( "Cannot use @TaskAction annotation on method %s.%s() because %s is not a valid parameter to an action method.", method.getDeclaringClass().getSimpleName(), method.getName(), parameterTypes[0])); } if (taskClassInfo.incremental) { throw new GradleException( String.format("Cannot have multiple @TaskAction methods accepting an %s parameter.", IncrementalTaskInputs.class.getSimpleName())); } taskClassInfo.incremental = true; } if (processedMethods.contains(method.getName())) { return; } taskClassInfo.taskActions.add(createActionFactory(method, parameterTypes)); processedMethods.add(method.getName()); }
From source file:de.taimos.dvalin.jaxrs.remote.RemoteServiceBeanPostProcessor.java
private InjectionMetadata buildResourceMetadata(Class<?> clazz) { LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>(); Class<?> targetClass = clazz; do {/* w ww . j a va 2 s. c o m*/ LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>(); for (Field field : targetClass.getDeclaredFields()) { if (field.isAnnotationPresent(RemoteService.class)) { if (Modifier.isStatic(field.getModifiers())) { throw new IllegalStateException( "@RemoteService annotation is not supported on static fields"); } currElements.add(new RemoteServiceElement(field, field, null)); } } for (Method method : targetClass.getDeclaredMethods()) { Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { continue; } if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (bridgedMethod.isAnnotationPresent(RemoteService.class)) { if (Modifier.isStatic(method.getModifiers())) { throw new IllegalStateException( "@RemoteService annotation is not supported on static methods"); } if (method.getParameterTypes().length != 1) { throw new IllegalStateException( "@RemoteService annotation requires a single-arg method: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new RemoteServiceElement(method, bridgedMethod, pd)); } } } elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while ((targetClass != null) && (targetClass != Object.class)); return new InjectionMetadata(clazz, elements); }
From source file:org.exoplatform.social.addons.test.AbstractCoreTest.java
@Override /**//from www . java2 s .c o m * Override to run the test and assert its state. * @throws Throwable if any exception is thrown */ protected void runTest() throws Throwable { String fName = getName(); assertNotNull("TestCase.fName cannot be null", fName); // Some VMs crash when calling getMethod(null,null); Method runMethod = null; try { // use getMethod to get all public inherited // methods. getDeclaredMethods returns all // methods of this class but excludes the // inherited ones. runMethod = getClass().getMethod(fName, (Class[]) null); } catch (NoSuchMethodException e) { fail("Method \"" + fName + "\" not found"); } if (!Modifier.isPublic(runMethod.getModifiers())) { fail("Method \"" + fName + "\" should be public"); } try { MaxQueryNumber queryNumber = runMethod.getAnnotation(MaxQueryNumber.class); if (queryNumber != null) { wantCount = true; maxQuery = queryNumber.value(); } runMethod.invoke(this); } catch (InvocationTargetException e) { e.fillInStackTrace(); throw e.getTargetException(); } catch (IllegalAccessException e) { e.fillInStackTrace(); throw e; } if (hasByteMan) { if (wantCount && count > maxQuery) { throw new AssertionFailedError( "" + count + " JDBC queries was executed but the maximum is : " + maxQuery); } } }
From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java
/** * TODO/*from w w w. ja va 2 s .co m*/ * * @param controllerClass The <code>Controller</code> class to search methods for. * @return a map containing the method's name as the key and its configuration as the value. * * @see org.apache.struts2.convention.annotation.Action * @see javax.ws.rs.Path * @see javax.ws.rs.HttpMethod * @see javax.ws.rs.GET * @see javax.ws.rs.POST * @see javax.ws.rs.PUT * @see javax.ws.rs.DELETE * @see javax.ws.rs.Consumes * @see javax.ws.rs.Produces */ protected Map<String, ActionMethodConfigBean> findActionMethods(Class<?> controllerClass) { Map<String, ActionMethodConfigBean> map = new HashMap<String, ActionMethodConfigBean>(); Method[] methods = controllerClass.getMethods(); for (Method method : methods) { // first of all, lets validate the candidate... Class<?> returnType = method.getReturnType(); if (returnType == null || (!returnType.equals(String.class) && !returnType.isAssignableFrom(Response.class)) || method.getParameterTypes().length > 0 || Modifier.isStatic(method.getModifiers())) { continue; } ActionMethodConfigBean methodConfig = new ActionMethodConfigBean(); methodConfig.setName(method.getName()); // Guessing http method String httpMethod = this.guessHttpMethod(method).value(); methodConfig.setHttpMethod(httpMethod); // if a @Action annotation is found then keep it for results, interceptors and so to be configured properly final Action actionAnnotation = ReflectionUtils.getAnnotation(Action.class, method); if (actionAnnotation != null) { methodConfig.setAction(actionAnnotation); methodConfig.setUriTemplate(actionAnnotation.value().trim()); } // if a @Path annotation is found then its value overwrites the @Action one (if found too) final Path pathAnnotation = ReflectionUtils.getAnnotation(Path.class, method); if (pathAnnotation != null) { methodConfig.setUriTemplate(pathAnnotation.value().trim()); } // are there any restrinctions for response type // methodConfig.setProduces(method.getAnnotation(Produces.class)); // TODO @Consumes // if no URI template found, then guess based on method's name if (StringUtils.isBlank(methodConfig.getUriTemplate())) { // TODO filter methods //methodConfig.setUriTemplate(actionNameBuilder.build(method.getName())); } else { map.put(method.getName(), methodConfig); } // map.put(method.getName(), methodConfig); TODO remove 'else' above after impl method filtering } return map; }
From source file:com.offbynull.coroutines.instrumenter.asm.InstructionUtils.java
/** * Calls a method with a set of arguments. After execution the stack may have an extra item pushed on it: the object that was returned * by this method (if any)./*from www.j a v a 2s. c o m*/ * @param method method to call * @param args method argument instruction lists -- each instruction list must leave one item on the stack of the type expected * by the method (note that if this is a non-static method, the first argument must always evaluate to the "this" pointer/reference) * @return instructions to invoke a method * @throws NullPointerException if any argument is {@code null} or array contains {@code null} * @throws IllegalArgumentException if the length of {@code args} doesn't match the number of parameters in {@code method} */ public static InsnList call(Method method, InsnList... args) { Validate.notNull(method); Validate.notNull(args); Validate.noNullElements(args); InsnList ret = new InsnList(); for (InsnList arg : args) { ret.add(arg); } Type clsType = Type.getType(method.getDeclaringClass()); Type methodType = Type.getType(method); if ((method.getModifiers() & Modifier.STATIC) == Modifier.STATIC) { Validate.isTrue(method.getParameterCount() == args.length); ret.add(new MethodInsnNode(Opcodes.INVOKESTATIC, clsType.getInternalName(), method.getName(), methodType.getDescriptor(), false)); } else if (method.getDeclaringClass().isInterface()) { Validate.isTrue(method.getParameterCount() + 1 == args.length); ret.add(new MethodInsnNode(Opcodes.INVOKEINTERFACE, clsType.getInternalName(), method.getName(), methodType.getDescriptor(), true)); } else { Validate.isTrue(method.getParameterCount() + 1 == args.length); ret.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, clsType.getInternalName(), method.getName(), methodType.getDescriptor(), false)); } return ret; }
From source file:com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl.java
private MethodAttribute computeMethodAttribute(Method method, Class<?> targetClass) { // Don't allow no-public methods as required. if (this.allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) { return null; }//from w ww . j a v a 2 s . c o m // The method may be on an interface, but we need attributes from the target class. // If the target class is null, the method will be unchanged. Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); // If we are dealing with method with generic parameters, find the original method. specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); // First try is the method in the target class. MethodAttribute att = this.findMethodAttribute(specificMethod); if (att != null) { return att; } if (specificMethod != method) { // Fallback is to look at the original method. att = this.findMethodAttribute(method); if (att != null) { return att; } } return null; }
From source file:org.evosuite.testcase.statements.FunctionalMockStatementTest.java
@Test public void testConfirmPackageLevel() throws Exception { Method m = AClassWithPLMethod.class.getDeclaredMethod("foo"); assertFalse(Modifier.isPrivate(m.getModifiers())); assertFalse(Modifier.isPublic(m.getModifiers())); assertFalse(Modifier.isProtected(m.getModifiers())); }
From source file:com.kjt.service.common.SoafwTesterMojo.java
private void genTest(String basedPath, String className) { // /*from www.j a v a2 s .c om*/ this.getLog().info("" + className + ""); Map<String, Integer> methodCnt = new HashMap<String, Integer>(); boolean hasmethod = false; try { Class cls = cl.loadClass(className); String testJFileName = cls.getSimpleName() + "Test.java"; String pkgPath = cls.getPackage().getName().replace(".", File.separator); String testJFilePath = basedPath + File.separator + "src" + File.separator + "test" + File.separator + "java" + File.separator + pkgPath; int len = 0; Class[] inters = cls.getInterfaces(); if (inters == null || (len = inters.length) == 0) { return; } /** * package import */ StringBuffer jHeadBuf = createTestJHeadByClass(cls); StringBuffer testJBuf = new StringBuffer(); testJBuf.append(jHeadBuf); Map<String, String> methodDefs = new HashMap<String, String>(); for (int j = 0; j < len; j++) { /** * ? */ Class interCls = inters[j]; this.getLog().info("@interface: " + interCls.getName()); String name = project.getName(); Method[] methods = null; if (name.endsWith("-dao")) { methods = interCls.getDeclaredMethods(); } else { methods = interCls.getMethods(); } int mlen = 0; if (methods != null && (mlen = methods.length) > 0) { this.getLog().info("?" + className + "Test?"); StringBuffer methodBuf = new StringBuffer(); for (int m = 0; m < mlen; m++) { Method method = methods[m]; int modf = method.getModifiers(); if (modf == 1025) {// ?? hasmethod = true; /** * ??????Test ???=??+Test * ??:basedPath+File.separator * +src+File.separator+test+File.separator * +pkg+definesArray[i]+Test+.java */ if (methodCnt.containsKey(method.getName())) { methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1); } else { methodCnt.put(method.getName(), 0); } int cnt = methodCnt.get(method.getName()); addMethod(methodDefs, methodBuf, method, cnt); } } testJBuf.append(methodBuf); } else { this.getLog().info(className + ""); } } String testJFile = testJBuf.append("}").toString(); if (hasmethod) { write(testJFilePath, testJFileName, testJFile); } } catch (Exception e) { this.getLog().error(e); } catch (Error er) { this.getLog().error(er); } }
From source file:de.codesourcery.springmass.springmass.SimulationParamsBuilder.java
private boolean isPartOfPublicInterface(Method m) { final int mods = m.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isAbstract(mods) || Modifier.isNative(mods) || !Modifier.isPublic(mods)) { return false; }/*from ww w . j av a 2 s . c o m*/ return true; }
From source file:de.taimos.dvalin.cloud.aws.AWSClientBeanPostProcessor.java
private InjectionMetadata buildResourceMetadata(Class<?> clazz) { LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<>(); Class<?> targetClass = clazz; do {/*from w w w . jav a2 s.com*/ LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<>(); for (Field field : targetClass.getDeclaredFields()) { if (field.isAnnotationPresent(AWSClient.class)) { if (Modifier.isStatic(field.getModifiers())) { throw new IllegalStateException("@AWSClient annotation is not supported on static fields"); } currElements.add(new AWSClientElement(field, null, field.getAnnotation(AWSClient.class))); } } for (Method method : targetClass.getDeclaredMethods()) { Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method); if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) { continue; } if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) { if (bridgedMethod.isAnnotationPresent(AWSClient.class)) { if (Modifier.isStatic(method.getModifiers())) { throw new IllegalStateException( "@AWSClient annotation is not supported on static methods"); } if (method.getParameterTypes().length != 1) { throw new IllegalStateException( "@AWSClient annotation requires a single-arg method: " + method); } PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz); currElements.add(new AWSClientElement(method, pd, method.getAnnotation(AWSClient.class))); } } } elements.addAll(0, currElements); targetClass = targetClass.getSuperclass(); } while ((targetClass != null) && (targetClass != Object.class)); return new InjectionMetadata(clazz, elements); }