List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:org.thiesen.helenaorm.HelenaColumnDAO.java
private boolean nullSafeAnnotationPresent(final Class<? extends Annotation> annotation, final Method method) { if (method != null) { if (method.isAnnotationPresent(annotation)) { return true; }/*from w w w .j a v a 2 s . co m*/ } return false; }
From source file:com.ecofactor.qa.automation.platform.ops.impl.AbstractDriverOperations.java
/** * Inject ops for listener.//from w w w . jav a2s . c o m * @param listenerName the listener name * @throws ClassNotFoundException the class not found exception * @throws IllegalAccessException the illegal access exception * @throws InvocationTargetException the invocation target exception */ private void injectOpsForListener(final String listenerName) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException { for (final Method method : this.getClass().getClassLoader().loadClass(listenerName).getMethods()) { if (method.isAnnotationPresent(BindOSOperation.class)) { method.invoke(null, this); } } }
From source file:com.corundumstudio.socketio.annotation.SpringAnnotationScanner.java
@Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { final AtomicBoolean add = new AtomicBoolean(); ReflectionUtils.doWithMethods(bean.getClass(), new MethodCallback() { @Override//from w ww . ja v a2 s . c om public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { add.set(true); } }, new MethodFilter() { @Override public boolean matches(Method method) { for (Class<? extends Annotation> annotationClass : annotations) { if (method.isAnnotationPresent(annotationClass)) { return true; } } return false; } }); if (add.get()) { originalBeanClass = bean.getClass(); } return bean; }
From source file:org.zodiark.server.ZodiarkObjectFactory.java
@Override public <T, U extends T> T newClassInstance(final AtmosphereFramework framework, Class<T> classType, Class<U> tClass) throws InstantiationException, IllegalAccessException { logger.debug("About to create {}", tClass.getName()); if (!added.getAndSet(true) && framework != null) { framework.getAtmosphereConfig().shutdownHook(new AtmosphereConfig.ShutdownHook() { @Override//w w w.jav a 2s . c o m public void shutdown() { timer.shutdown(); } }); framework.getAtmosphereConfig().startupHook(new AtmosphereConfig.StartupHook() { @Override public void started(AtmosphereFramework framework) { injectRepository.clear(); implementationRepository.clear(); instanceRepository.clear(); } }); } Class<? extends T> impl = implement(classType); boolean needsPostConstruct = (impl == null || instanceRepository.get(impl) == null); T instance = impl != null ? newInstance(impl) : tClass.newInstance(); Field[] fields = tClass.equals(instance.getClass()) ? tClass.getDeclaredFields() : impl.getFields(); for (Field field : fields) { if (field.isAnnotationPresent(Inject.class)) { if (field.getType().isAssignableFrom(ObjectMapper.class)) { field.set(instance, inject(ObjectMapper.class)); } else if (field.getType().isAssignableFrom(EventBus.class)) { field.set(instance, inject(EventBus.class)); } else if (field.getType().isAssignableFrom(RestService.class)) { field.set(instance, newClassInstance(framework, RestService.class, RestService.class)); } else if (field.getType().isAssignableFrom(WowzaEndpointManager.class)) { field.set(instance, inject(WowzaEndpointManager.class)); } else if (field.getType().isAssignableFrom(Context.class)) { field.set(instance, new Context() { @Override public <T> T newInstance(Class<T> t) { try { return newClassInstance(framework, t, t); } catch (Exception e) { throw new RuntimeException(e); } } }); } else if (field.getType().isAssignableFrom(AuthConfig.class)) { field.set(instance, newClassInstance(framework, Result.class, AuthConfig.class)); } else if (field.getType().isAssignableFrom(EndpointState.class)) { field.set(instance, newClassInstance(framework, EndpointState.class, EndpointState.class)); } else if (field.getType().isAssignableFrom(StreamingRequest.class)) { field.set(instance, inject(StreamingRequest.class)); } else if (field.getType().isAssignableFrom(ScheduledExecutorService.class)) { field.set(instance, timer); } else if (field.getType().isAssignableFrom(RestClient.class)) { field.set(instance, newClassInstance(framework, RestClient.class, RestClient.class)); } else if (field.getType().isAssignableFrom(URI.class)) { field.set(instance, inject(URI.class)); } } } if (needsPostConstruct) { Method[] methods = tClass.equals(instance.getClass()) ? tClass.getMethods() : instance.getClass().getMethods(); for (Method m : methods) { if (m.isAnnotationPresent(PostConstruct.class)) { try { m.invoke(instance); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } } return instance; }
From source file:de.matzefratze123.heavyspleef.core.flag.FlagRegistry.java
public void registerFlag(Class<? extends AbstractFlag<?>> clazz) { Validate.notNull(clazz, "clazz cannot be null"); Validate.isTrue(!registeredFlagsMap.containsValue(clazz), "Cannot register flag twice"); /* Check if the class provides the required Flag annotation */ Validate.isTrue(clazz.isAnnotationPresent(Flag.class), "Flag-Class must be annotated with the @Flag annotation"); Flag flagAnnotation = clazz.getAnnotation(Flag.class); String name = flagAnnotation.name(); Validate.isTrue(!name.isEmpty(),/*w w w .j a va 2s .c om*/ "name() of annotation of flag for class " + clazz.getCanonicalName() + " cannot be empty"); /* Generate a path */ StringBuilder pathBuilder = new StringBuilder(); Flag parentFlagData = flagAnnotation; do { pathBuilder.insert(0, parentFlagData.name()); Class<? extends AbstractFlag<?>> parentFlagClass = parentFlagData.parent(); parentFlagData = parentFlagClass.getAnnotation(Flag.class); if (parentFlagData != null && parentFlagClass != NullFlag.class) { pathBuilder.insert(0, FLAG_PATH_SEPERATOR); } } while (parentFlagData != null); String path = pathBuilder.toString(); /* Check for name collides */ for (String flagPath : registeredFlagsMap.primaryKeySet()) { if (flagPath.equalsIgnoreCase(path)) { throw new IllegalArgumentException( "Flag " + clazz.getName() + " collides with " + registeredFlagsMap.get(flagPath).getName()); } } /* Check if the class can be instantiated */ try { Constructor<? extends AbstractFlag<?>> constructor = clazz.getDeclaredConstructor(); //Make the constructor accessible for future uses constructor.setAccessible(true); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException("Flag-Class must provide an empty constructor"); } HookManager hookManager = heavySpleef.getHookManager(); boolean allHooksPresent = true; for (HookReference ref : flagAnnotation.depend()) { if (!hookManager.getHook(ref).isProvided()) { allHooksPresent = false; } } if (allHooksPresent) { for (Method method : clazz.getDeclaredMethods()) { if (!method.isAnnotationPresent(FlagInit.class)) { continue; } if ((method.getModifiers() & Modifier.STATIC) == 0) { throw new IllegalArgumentException("Flag initialization method " + method.getName() + " in type " + clazz.getCanonicalName() + " is not declared as static"); } queuedInitMethods.add(method); } if (flagAnnotation.hasCommands()) { CommandManager manager = heavySpleef.getCommandManager(); manager.registerSpleefCommands(clazz); } } registeredFlagsMap.put(path, flagAnnotation, clazz); }
From source file:de.jackwhite20.japs.client.sub.impl.SubscriberImpl.java
@Override public void subscribeMulti(Class<?> handler) { // Get channel and check the class for annotation etc. String channel = getChannelFromAnnotation(handler); try {//from w ww . ja v a 2 s .c o m List<MultiHandlerInfo.Entry> entries = new ArrayList<>(); Object object = handler.newInstance(); for (Method method : object.getClass().getDeclaredMethods()) { if (method.getParameterCount() == 1) { if (method.isAnnotationPresent(Key.class) && method.isAnnotationPresent(Value.class)) { entries.add(new MultiHandlerInfo.Entry(method.getAnnotation(Key.class), method.getAnnotation(Value.class), method.getParameterTypes()[0], (method.getParameterTypes()[0].getSimpleName().equals("JSONObject")) ? ClassType.JSON : ClassType.GSON, method)); } } } multiHandlers.put(channel, new MultiHandlerInfo(entries, object)); JSONObject jsonObject = new JSONObject().put("op", OpCode.OP_REGISTER_CHANNEL.getCode()).put("ch", channel); write(jsonObject, false); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.urbanmania.spring.beans.factory.config.annotations.PropertyAnnotationAndPlaceholderConfigurer.java
private void processAnnotatedProperties(Properties properties, String name, MutablePropertyValues mpv, Class<?> clazz) {//from w w w. j a va 2s . com // TODO support proxies if (clazz != null && clazz.getPackage() != null) { if (basePackage != null && !clazz.getPackage().getName().startsWith(basePackage)) { return; } log.info("Configuring properties for bean=" + name + "[" + clazz + "]"); for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) { if (log.isLoggable(Level.FINE)) log.fine("examining property=[" + clazz.getName() + "." + property.getName() + "]"); Method setter = property.getWriteMethod(); Method getter = property.getReadMethod(); Property annotation = null; if (setter != null && setter.isAnnotationPresent(Property.class)) { annotation = setter.getAnnotation(Property.class); } else if (setter != null && getter != null && getter.isAnnotationPresent(Property.class)) { annotation = getter.getAnnotation(Property.class); } else if (setter == null && getter != null && getter.isAnnotationPresent(Property.class)) { throwBeanConfigurationException(clazz, property.getName()); } if (annotation != null) { setProperty(properties, name, mpv, clazz, property, annotation); } } for (Field field : clazz.getDeclaredFields()) { if (log.isLoggable(Level.FINE)) log.fine("examining field=[" + clazz.getName() + "." + field.getName() + "]"); if (field.isAnnotationPresent(Property.class)) { Property annotation = field.getAnnotation(Property.class); PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName()); if (property == null || property.getWriteMethod() == null) { throwBeanConfigurationException(clazz, field.getName()); } setProperty(properties, name, mpv, clazz, property, annotation); } } } }
From source file:org.apache.hadoop.hdfs.storageservice.NNLatencyBenchmark.java
@Override public int run(String[] args) throws Exception { parseArgs(args);/*from w ww . j a v a2 s . co m*/ // Create results file FileWriter results = new FileWriter(resultsFile, true); // Run all benchmarks int failed = 0; for (Method method : NNLatencyBenchmark.class.getMethods()) { if (method.isAnnotationPresent(Benchmark.class)) { results.write(method.getName() + " : "); try { setUp(); try { method.invoke(this, results); } finally { tearDown(); } } catch (Throwable e) { failed++; LOG.error(method.getName() + " failed with: ", e); } results.write("\n"); } } results.close(); return -failed; }
From source file:de.cubeisland.engine.module.stats.StatsManager.java
/** * Register a statistic.//w w w. j ava 2 s . c om * This will make this StatsManager handle the statistic's database connection * and register it as a listener. * * @param statType The stat class to register */ public void register(Class<? extends Stat> statType) { if (!this.started) { throw new IllegalStateException("StatsManager not started!"); } try { // Get the Constructor, and construct a new instance of the Stat. Constructor<? extends Stat> constructor = statType.getConstructor(); Stat stat = constructor.newInstance(); Method init = statType.getMethod("init", this.getClass(), Module.class); init.invoke(stat, this, this.module); // Get or register the stat in the database if (!registeredStats.contains(statType)) { synchronized (this.dsl) { StatsModel model = this.dsl.newRecord(TABLE_STATS).newStatsModel(statType.getName()); model.insert(); registeredStats.add(statType); } } this.stats.put(statType, stat); // Load configured fields for (Field field : statType.getFields()) { if (!field.isAnnotationPresent(Configured.class)) { return; } String name = field.getName(); String[] comment = {}; if (field.isAnnotationPresent(Name.class)) { Name nameAnnotation = field.getAnnotation(Name.class); name = nameAnnotation.value(); } if (field.isAnnotationPresent(Comment.class)) { Comment commentAnnotation = field.getAnnotation(Comment.class); comment = commentAnnotation.value(); } if (!module.getConfig().statConfigs.containsKey(statType.getSimpleName())) { module.getConfig().statConfigs.put(statType.getSimpleName(), new DynamicSection(converterManager)); } DynamicSection section = module.getConfig().statConfigs.get(statType.getSimpleName()); if (section.hasKey(name)) { section.getNode(name).setComments(comment); field.set(stat, section.get(name)); } else { section.put(name, field.get(stat), comment); } } // Activate hook in the stat stat.activate(); // Register Schedulers for (Method method : stat.getClass().getMethods()) { if (!method.isAnnotationPresent(Scheduled.class)) { continue; } Scheduled annotation = method.getAnnotation(Scheduled.class); long interval; if (annotation.periodFinal()) { interval = annotation.interval(); } else { if (!module.getConfig().statConfigs.containsKey(statType.getSimpleName())) { module.getConfig().statConfigs.put(statType.getSimpleName(), new DynamicSection(converterManager)); } DynamicSection section = module.getConfig().statConfigs.get(statType.getSimpleName()); if (!section.hasKey("tasks")) { section.put("tasks", new DynamicSection(converterManager), "Intervals for the tasks this statistic schedules"); } else { section.getNode("tasks") .setComments(new String[] { "Intervals for the tasks this statistic schedules" }); } DynamicSection tasks = (DynamicSection) section.get("tasks", DynamicSection.class); if (!tasks.hasKey(annotation.name())) { tasks.put(annotation.name(), annotation.interval(), annotation.comment()); } else { tasks.getNode(annotation.name()).setComments(annotation.comment()); } interval = (Long) tasks.get(annotation.name(), Long.class); } if (!this.tasks.containsKey(statType)) { this.tasks.put(statType, new HashSet<Integer>()); } Set<Integer> tasks = this.tasks.get(statType); Runnable wrapper = new ScheduledMethod(this.module.getLog(), stat, method); TaskManager taskManager = module.getCore().getTaskManager(); if (annotation.async()) { tasks.add(taskManager.runAsynchronousTimer(module, wrapper, 1, interval)); } else { tasks.add(taskManager.runTimer(module, wrapper, 1, interval)); } this.module.getLog().debug("Scheduled method {} at interval {}", annotation.name(), interval); } } catch (ReflectiveOperationException | ConversionException ex) { this.module.getLog().error(ex, "An error occurred while registering statistic"); } this.module.getLog().debug("Registered statistic {}.", statType.getSimpleName()); }
From source file:gobblin.runtime.cli.PublicMethodsCliObjectFactory.java
private boolean canUseMethod(Method method) { if (!Modifier.isPublic(method.getModifiers())) { return false; }//from w w w . ja v a2s .c o m if (BLACKLISTED_FROM_CLI.contains(method.getName())) { return false; } if (method.isAnnotationPresent(NotOnCli.class)) { return false; } Class<?>[] parameters = method.getParameterTypes(); if (parameters.length >= 2) { return false; } if (parameters.length == 1 && parameters[0] != String.class) { return false; } return true; }