List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:org.okj.commons.web.json.interceptor.JSONOutputterInterceptor.java
/** * /* ww w.ja va 2 s .c o m*/ * @param handler * @param annotationClass * @return */ protected Set<Method> findHandlerMethods(Object handler, final Class<? extends Annotation> annotationClass) { final Set<Method> handlerMethods = new HashSet<Method>(); //class final Class<?> handlerClass = ClassUtils.getUserClass(handler); //handlerJsonResulthandlerMethods ReflectionUtils.doWithMethods(handlerClass, new ReflectionUtils.MethodCallback() { public void doWith(Method method) { if (method.isAnnotationPresent(annotationClass)) { Method m = ClassUtils.getMostSpecificMethod(method, handlerClass); handlerMethods.add(m); } } }); return handlerMethods; }
From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java
private Map<String, SpringResource> analyzeController(Class<?> clazz, Map<String, SpringResource> resourceMap, String description) throws ClassNotFoundException { for (int i = 0; i < clazz.getAnnotation(RequestMapping.class).value().length; i++) { String controllerMapping = clazz.getAnnotation(RequestMapping.class).value()[i]; String resourceName = Utils.parseResourceName(clazz); for (Method m : clazz.getMethods()) { if (m.isAnnotationPresent(RequestMapping.class)) { RequestMapping methodReq = m.getAnnotation(RequestMapping.class); if (methodReq.value() == null || methodReq.value().length == 0 || Utils.parseResourceName(methodReq.value()[0]).equals("")) { if (resourceName.length() != 0) { String resourceKey = Utils.createResourceKey(resourceName, Utils.parseVersion(controllerMapping)); if ((!(resourceMap.containsKey(resourceKey)))) { resourceMap.put(resourceKey, new SpringResource(clazz, resourceName, resourceKey, description)); }//from w w w. j ava 2 s . c om resourceMap.get(resourceKey).addMethod(m); } } } } } clazz.getFields(); clazz.getDeclaredFields(); //<--In case developer declares a field without an associated getter/setter. //this will allow NoClassDefFoundError to be caught before it triggers bamboo failure. return resourceMap; }
From source file:test.org.wildfly.swarm.microprofile.openapi.TckTestRunner.java
/** * Creates and returns the shrinkwrap archive for this test. *//*from ww w.j av a2s . c o m*/ private Archive archive() throws InitializationError { try { Method[] methods = tckTestClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(Deployment.class)) { Archive archive = (Archive) method.invoke(null); return archive; } } throw new Exception("No @Deployment archive found for test."); } catch (Exception e) { throw new InitializationError(e); } }
From source file:com.jayway.jaxrs.hateoas.DefaultHateoasContext.java
private String findHttpMethod(Method method) { if (method.isAnnotationPresent(GET.class)) { return HttpMethod.GET; }/*w w w .ja va2 s . co m*/ if (method.isAnnotationPresent(POST.class)) { return HttpMethod.POST; } if (method.isAnnotationPresent(PUT.class)) { return HttpMethod.PUT; } if (method.isAnnotationPresent(DELETE.class)) { return HttpMethod.DELETE; } if (method.isAnnotationPresent(OPTIONS.class)) { return HttpMethod.OPTIONS; } return null; }
From source file:gobblin.runtime.cli.PublicMethodsGobblinCliFactory.java
private Options inferOptionsFromMethods() { Options options = new Options(); for (Method method : klazz.getMethods()) { if (canUseMethod(method)) { EmbeddedGobblinCliOption annotation = method.isAnnotationPresent(EmbeddedGobblinCliOption.class) ? method.getAnnotation(EmbeddedGobblinCliOption.class) : null;/* www. j a v a2 s. c o m*/ String optionName = annotation == null || Strings.isNullOrEmpty(annotation.name()) ? method.getName() : annotation.name(); String description = annotation == null ? "" : annotation.description(); Option.Builder builder = Option.builder(optionName).desc(description); boolean hasArg = method.getParameterTypes().length > 0; if (hasArg) { builder.hasArg(); } Option option = builder.build(); options.addOption(option); this.methodsMap.put(option.getOpt(), method); } } return options; }
From source file:com.flowpowered.cerealization.config.annotated.AnnotatedObjectConfiguration.java
private void save(ConfigurationNodeSource source, Object object, String[] path, Set<Member> members) throws ConfigurationException { final Set<Method> methods = new HashSet<Method>(); for (Member member : members) { if (member instanceof Method) { final Method method = (Method) member; if (method.isAnnotationPresent(Save.class)) { methods.add(method);/* w ww .jav a2 s. c o m*/ } continue; } final Field field = (Field) member; field.setAccessible(true); String[] fieldPath = field.getAnnotation(Setting.class).value(); if (fieldPath.length == 0) { fieldPath = new String[] { field.getName() }; } final ConfigurationNode fieldNode = source.getNode(ArrayUtils.addAll(path, fieldPath)); try { fieldNode.setValue(field.getGenericType(), field.get(object)); } catch (IllegalAccessException ex) { throw new ConfigurationException(ex); } } invokeMethods(methods, object, source.getNode(path)); }
From source file:mitm.common.hibernate.AutoCommitProxyFactory.java
private void findInjectMethods(Class<T> clazz) throws NoSuchMethodException { Method[] methods = clazz.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(InjectHibernateSession.class)) { String parameterDescriptor = RuntimeSupport.makeDescriptor(method); if (!parameterDescriptor.equals("(Lorg/hibernate/Session;)V")) { throw new NoSuchMethodException( "@InjectHibernateSession method does not have the correct parameters."); }/*from w w w . j a v a 2 s.c o m*/ injectHibernateSessionMethod = method; } else if (method.isAnnotationPresent(InjectHibernateSessionSource.class)) { String parameterDescriptor = RuntimeSupport.makeDescriptor(method); if (!parameterDescriptor.equals("(Lmitm/common/hibernate/HibernateSessionSource;)V")) { throw new NoSuchMethodException( "@InjectHibernateSessionSource method does not have the correct parameters."); } injectHibernateSessionSourceMethod = method; } } }
From source file:test.org.wildfly.swarm.microprofile.openapi.TckTestRunner.java
/** * @see org.junit.runners.ParentRunner#getChildren() *//*from ww w . ja va2s .co m*/ @Override protected List<ProxiedTckTest> getChildren() { List<ProxiedTckTest> children = new ArrayList<>(); Method[] methods = tckTestClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(org.testng.annotations.Test.class)) { try { ProxiedTckTest test = new ProxiedTckTest(); Object theTestObj = this.testClass.newInstance(); test.setTest(theTestObj); test.setTestMethod(method); test.setDelegate(createDelegate(theTestObj)); children.add(test); } catch (Exception e) { throw new RuntimeException(e); } } } children.sort(new Comparator<ProxiedTckTest>() { @Override public int compare(ProxiedTckTest o1, ProxiedTckTest o2) { return o1.getTestMethod().getName().compareTo(o2.getTestMethod().getName()); } }); return children; }
From source file:com.hubspot.utils.circuitbreaker.CircuitBreakerWrapper.java
/** * Wraps the supplied object toWrap in a CircuitBreaker conforming to the supplied CircuitBreakerPolicy. *//*from ww w . j a v a2 s. c o m*/ public <T, W extends T> T wrap(W toWrap, Class<T> interfaceToProxy, CircuitBreakerPolicy policy) throws CircuitBreakerWrappingException { sanityCheck(toWrap, interfaceToProxy, policy); // walk the chain of interfaces implemented by T and check for their blacklisted methods Stack<Class<?>> implementedInterfaces = new Stack<Class<?>>(); implementedInterfaces.addAll(Arrays.asList(interfaceToProxy.getInterfaces())); implementedInterfaces.add(interfaceToProxy); Map<Method, Class[]> blacklist = new HashMap(); while (!implementedInterfaces.isEmpty()) { Class<?> implementedInterface = implementedInterfaces.pop(); for (Method m : implementedInterface.getDeclaredMethods()) { // check that the blacklisted method throws CircuitBreakerException if (m.isAnnotationPresent(CircuitBreakerExceptionBlacklist.class)) { if (!ArrayUtils.contains(m.getExceptionTypes(), CircuitBreakerException.class)) { throw new CircuitBreakerWrappingException( "Wrapped methods must throw CircuitBreakerException"); } CircuitBreakerExceptionBlacklist a = (CircuitBreakerExceptionBlacklist) m .getAnnotation(CircuitBreakerExceptionBlacklist.class); blacklist.put(m, a.blacklist()); } } implementedInterfaces.addAll(Arrays.asList(implementedInterface.getInterfaces())); } Class<?>[] interfaces = new Class<?>[] { interfaceToProxy }; InvocationHandler handler = new CircuitBreakerInvocationHandler(toWrap, blacklist, policy); T newProxyInstance = (T) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, handler); return newProxyInstance; }
From source file:uk.jamierocks.zinc.CommandService.java
/** * Registers all the commands from the given holder. * * @param plugin the owning plugin.//from w ww. j a v a 2 s. co m * @param holder the command holder. */ public void registerCommands(Object plugin, Object holder) { Map<CommandCallable, Command> subCommands = Maps.newHashMap(); Logger pluginLogger = LoggerFactory.getLogger(plugin.getClass()); for (Method method : holder.getClass().getDeclaredMethods()) { if (method.isAnnotationPresent(Command.class)) { Command command = method.getAnnotation(Command.class); if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == CommandSource.class && method.getParameterTypes()[1] == CommandArgs.class && method.getReturnType() == CommandResult.class) { CommandCallable commandCallable = new ZincCommandCallable(pluginLogger, command, holder, method); if (StringUtils.isEmpty(command.parent())) { this.game.getCommandManager().register(plugin, new ZincDispatcher(commandCallable), Lists.asList(command.name(), command.aliases())); } else { subCommands.put(commandCallable, command); } } else { if (method.getReturnType() != CommandResult.class) { ZINC_LOGGER.error(String.format("Command has wrong return type: %s#%s Should be %s", holder.getClass().getName(), method.getName(), CommandResult.class.getName())); } if (method.getParameterTypes().length != 2 || method.getParameterTypes()[0] != CommandSource.class || method.getParameterTypes()[1] != CommandArgs.class) { ZINC_LOGGER.error( String.format("Command has wrong argument types: %s#%s Should have %s and %s", holder.getClass().getName(), method.getName(), CommandSource.class.getName(), CommandArgs.class.getName())); } } } else if (method.isAnnotationPresent(TabComplete.class)) { TabComplete tabComplete = method.getAnnotation(TabComplete.class); if (method.getParameterTypes().length == 2 && method.getParameterTypes()[0] == CommandSource.class && method.getParameterTypes()[1] == String.class && method.getReturnType() == List.class) { final ZincDispatcher.SuggestionHandler suggestionHandler = (src, arguments) -> { try { return (List<String>) method.invoke(holder, src, arguments); } catch (IllegalAccessException e) { pluginLogger.error("Failed to invoke instance", e); } catch (InvocationTargetException e) { pluginLogger.error("Failed to invoke instance", e); } return Lists.newArrayList(); }; if (this.game.getCommandManager().get(tabComplete.name()).isPresent() && this.game.getCommandManager().get(tabComplete.name()).get() .getCallable() instanceof ZincDispatcher) { ZincDispatcher dispatcher = (ZincDispatcher) this.game.getCommandManager() .get(tabComplete.name()).get().getCallable(); dispatcher.setSuggestionHandler(suggestionHandler); } else { ZINC_LOGGER.error(String.format( "Tab complete attempted to register, but parent command wasn't found: %s", tabComplete.name())); } } else { if (method.getReturnType() != List.class) { ZINC_LOGGER.error(String.format("Tab complete has wrong return type: %s#%s Should be %s", holder.getClass().getName(), method.getName(), List.class.getName())); } if (method.getParameterTypes().length != 2 || method.getParameterTypes()[0] != CommandSource.class || method.getParameterTypes()[1] != String.class) { ZINC_LOGGER.error( String.format("Tab complete has wrong argument types: %s#%s Should have %s and %s", holder.getClass().getName(), method.getName(), CommandSource.class.getName(), String.class.getName())); } } } } for (CommandCallable commandCallable : subCommands.keySet()) { Command command = subCommands.get(commandCallable); if (this.game.getCommandManager().get(command.parent()).isPresent() && this.game.getCommandManager() .get(command.parent()).get().getCallable() instanceof ZincDispatcher) { ZincDispatcher dispatcher = (ZincDispatcher) this.game.getCommandManager().get(command.parent()) .get().getCallable(); dispatcher.register(commandCallable, Lists.asList(command.name(), command.aliases())); } else { ZINC_LOGGER.error(String.format("Sub command was registered, but parent command wasn't found: %s", command.parent())); } } }