List of usage examples for java.lang.reflect Method getModifiers
@Override public int getModifiers()
From source file:ninja.eivind.hotsreplayuploader.ClientTest.java
@Test public void testClientIsMainClass() throws Exception { String className = parse.select("project > properties > mainClass").text(); LOG.info("Loading class " + className); Class<?> mainClass = Class.forName(className); Method main = mainClass.getDeclaredMethod("main", String[].class); int modifiers = main.getModifiers(); Class<?> returnType = main.getReturnType(); assertEquals("Client is mainClass", Client.class, mainClass); assertSame("Main method returns void", returnType, Void.TYPE); assertTrue("Main method is static", Modifier.isStatic(modifiers)); assertTrue("Main method is public", Modifier.isPublic(modifiers)); }
From source file:com.laxser.blitz.web.impl.module.ErrorHandlerDispatcher.java
public ErrorHandlerDispatcher(ControllerErrorHandler errorHandler) { this.errorHandler = errorHandler; Method[] methods = this.errorHandler.getClass().getMethods(); for (final Method method : methods) { if (Modifier.isAbstract(method.getModifiers()) || Modifier.isStatic(method.getModifiers())) { continue; }/*from w ww . j a va2 s .c om*/ if (method.getName().equals("onError")) { final Class<?>[] parameterClasses = method.getParameterTypes(); if (parameterClasses.length == 2 && parameterClasses[INVOCATION_INDEX] == Invocation.class && Throwable.class.isAssignableFrom(parameterClasses[THROWABLE_INDEX])) { delegates.add(new ErrorHandlerDelegate() { @Override public Method getMethod() { return method; } @Override public Object onError(Invocation inv, Throwable ex) throws Throwable { Object[] args = new Object[] { inv, ex }; try { return method.invoke(ErrorHandlerDispatcher.this.errorHandler, args); } catch (Throwable e) { logger.error("error happened when handling error " + ex.getClass() + " at " + ErrorHandlerDispatcher.this.toString()); throw e; } } }); } } } Collections.sort(delegates, new Comparator<ErrorHandlerDelegate>() { @Override public int compare(ErrorHandlerDelegate o1, ErrorHandlerDelegate o2) { if (o1.getMethod().getParameterTypes()[THROWABLE_INDEX] .isAssignableFrom(o2.getMethod().getParameterTypes()[THROWABLE_INDEX])) { return 1; } else if (o2.getMethod().getParameterTypes()[THROWABLE_INDEX] .isAssignableFrom(o1.getMethod().getParameterTypes()[THROWABLE_INDEX])) { return -1; } else { return o1.getMethod().getParameterTypes()[THROWABLE_INDEX].getName() .compareTo(o2.getMethod().getParameterTypes()[THROWABLE_INDEX].getName()); } } }); }
From source file:org.apache.pig.JVMReuseManager.java
public void registerForStaticDataCleanup(Class<?> clazz) { for (Method method : clazz.getMethods()) { if (method.isAnnotationPresent(StaticDataCleanup.class)) { if (!(Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers()))) { throw new RuntimeException("Method " + method.getName() + " in class " + clazz.getName() + "should be public and static as it is annotated with "); }/*from www . jav a2s .co m*/ LOG.debug("Method " + method.getName() + " in class " + method.getDeclaringClass() + " registered for static data cleanup"); instance.cleanupMethods.add(method); } } }
From source file:org.enerj.apache.commons.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./*w ww.j a va 2 s. com*/ * 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 */ public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) { // trace logging 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 = (Method) cache.get(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())); } try { // // XXX Default access superclass workaround // // When a public class has a default access superclass // with public methods, these methods are accessible. // Calling them from compiled code works fine. // // Unfortunately, using reflection to invoke these methods // seems to (wrongly) to prevent access even when the method // modifer is public. // // The following workaround solves the problem but will only // work from sufficiently privilages code. // // Better workarounds would be greatfully accepted. // method.setAccessible(true); } catch (SecurityException se) { // log but continue just in case the method.invoke works anyway if (!loggedAccessibleWarning) { boolean vunerableJVM = false; try { String specVersion = System.getProperty("java.specification.version"); if (specVersion.charAt(0) == '1' && (specVersion.charAt(0) == '0' || specVersion.charAt(0) == '1' || specVersion.charAt(0) == '2' || specVersion.charAt(0) == '3')) { vunerableJVM = true; } } catch (SecurityException e) { // don't know - so display warning vunerableJVM = true; } if (vunerableJVM) { log.warn("Current Security Manager restricts use of workarounds for reflection bugs " + " in pre-1.4 JVMs."); } loggedAccessibleWarning = true; } log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se); } cache.put(md, method); return method; } catch (NoSuchMethodException e) { /* SWALLOW */ } // search through all methods int paramSize = parameterTypes.length; Method[] methods = clazz.getMethods(); 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(methods[i]); if (method != null) { if (log.isTraceEnabled()) { log.trace(method + " accessible version of " + methods[i]); } try { // // XXX Default access superclass workaround // (See above for more details.) // method.setAccessible(true); } catch (SecurityException se) { // log but continue just in case the method.invoke works anyway if (!loggedAccessibleWarning) { log.warn( "Cannot use JVM pre-1.4 access bug workaround due to restrictive security manager."); loggedAccessibleWarning = true; } log.debug( "Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se); } cache.put(md, method); return method; } log.trace("Couldn't find accessible method."); } } } } // didn't find a match log.trace("No match found."); return null; }
From source file:org.apache.ambari.server.utils.TestShellCommandUtil.java
public void testResultsClassIsPublic() throws Exception { Class resultClass = ShellCommandUtil.Result.class; assertEquals(Modifier.PUBLIC, resultClass.getModifiers() & Modifier.PUBLIC); for (Method method : resultClass.getMethods()) { assertEquals(method.getName(), Modifier.PUBLIC, (method.getModifiers() & Modifier.PUBLIC)); }//from ww w . j a v a 2 s .c om }
From source file:net.abhinavsarkar.spelhelper.ImplicitMethodResolver.java
@Override public MethodExecutor resolve(final EvaluationContext context, final Object targetObject, final String name, final List<TypeDescriptor> argumentTypes) throws AccessException { if (targetObject == null) { return null; }//from w ww.jav a 2 s . co m Class<?> type = targetObject.getClass(); String cacheKey = type.getName() + "." + name; if (CACHE.containsKey(cacheKey)) { MethodExecutor executor = CACHE.get(cacheKey); return executor == NULL_ME ? null : executor; } Method method = lookupMethod(context, type, name); if (method != null) { int modifiers = method.getModifiers(); if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) { Class<?>[] parameterTypes = method.getParameterTypes(); Class<?> firstParamType = parameterTypes[0]; if (parameterTypes.length > 0 && firstParamType.isAssignableFrom(type)) { List<TypeDescriptor> newArgumentTypes = new ArrayList<TypeDescriptor>(); newArgumentTypes.add(TypeDescriptor.valueOf(firstParamType)); newArgumentTypes.addAll(argumentTypes); MethodExecutor executor = delegate.resolve(context, method.getDeclaringClass(), name, newArgumentTypes); MethodExecutor wrappedExecutor = executor == null ? null : new ImplicitMethodExecutor(executor); if (wrappedExecutor == null) { CACHE.putIfAbsent(cacheKey, NULL_ME); } return wrappedExecutor; } } } CACHE.putIfAbsent(cacheKey, NULL_ME); return null; }
From source file:com.alibaba.dubbo.demo.consumer.DemoAction.java
public DubboBenchmark.BenchmarkMessage prepareArgs() throws InvocationTargetException, IllegalAccessException { boolean b = true; int i = 100000; String s = "??"; DubboBenchmark.BenchmarkMessage.Builder builder = DubboBenchmark.BenchmarkMessage.newBuilder(); Method[] methods = builder.getClass().getDeclaredMethods(); for (Method m : methods) { if (m.getName().startsWith("setField") && ((m.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC)) { Parameter[] params = m.getParameters(); if (params.length == 1) { String n = params[0].getParameterizedType().getTypeName(); m.setAccessible(true);// w ww.j a va 2 s . co m if (n.endsWith("java.lang.String")) { m.invoke(builder, new Object[] { s }); } else if (n.endsWith("int")) { m.invoke(builder, new Object[] { i }); } else if (n.equals("boolean")) { m.invoke(builder, new Object[] { b }); } } } } return builder.build(); }
From source file:org.apache.solr.update.processor.UpdateIndexAuthorizationProcessorTest.java
/** * Ensure no new methods have been added to base class that are not invoking * Sentry/* w w w . j a v a2 s.c om*/ */ @Test public void testAllMethodsChecked() throws Exception { Method[] methods = UpdateRequestProcessor.class.getDeclaredMethods(); TreeSet<String> foundNames = new TreeSet<String>(); for (Method method : methods) { if (Modifier.isPublic(method.getModifiers())) { foundNames.add(method.getName()); } } assertEquals(methodNames.size(), foundNames.size()); assertTrue(foundNames.containsAll(methodNames)); }
From source file:com.glaf.core.util.ReflectUtils.java
public static Object invoke(Object object, String methodName) { try {//ww w . j av a 2s . c om Method method = ReflectionUtils.findMethod(object.getClass(), methodName); if (!Modifier.isPublic(method.getModifiers())) { method.setAccessible(true); } return ReflectionUtils.invokeMethod(method, object); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:de.micromata.genome.util.matcher.cls.ContainsMethod.java
/** * Match this class./* w ww. j a v a 2 s .co m*/ * * @param cls the cls * @return true, if successful */ public boolean matchThisClass(Class<?> cls) { for (Method m : cls.getMethods()) { int mods = m.getModifiers(); if (staticMethod == true && (mods & Modifier.STATIC) != Modifier.STATIC) { continue; } if (staticMethod == false && (mods & Modifier.STATIC) == Modifier.STATIC) { continue; } if (publicMethod == true && (mods & Modifier.PUBLIC) != Modifier.PUBLIC) { continue; } if (name != null) { if (StringUtils.equals(m.getName(), name) == false) { continue; } } if (returnType != null) { if (m.getReturnType() != returnType) { continue; } } if (params != null) { Class<?>[] pt = m.getParameterTypes(); if (pt.length != params.length) { continue; } for (int i = 0; i < pt.length; ++i) { if (pt[i] != params[i]) { continue; } } } return true; } return false; }