Java Code Examples for java.lang.reflect.Method.isAnnotationPresent()

The following are Jave code examples for showing how to use isAnnotationPresent() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: McLink   File: VCommand.java   View Source Code Vote up 6 votes
@Override
public boolean execute(CommandSender arg0, String arg1, String[] arg2) {
	for (Method m : c.getDeclaredMethods()) {
		if (m.isAnnotationPresent(Command.Subcommand.class) && CommandConstruct.match(arg2, m.getAnnotation(Command.Subcommand.class).args())) {
			try {
				if (m.getAnnotation(Command.Subcommand.class).permission().equals("_")) {
					m.invoke(ins, arg0, arg1, arg2);
					return true;
				} else if (arg0.hasPermission(m.getAnnotation(Command.Subcommand.class).permission())) {
					m.invoke(ins, arg0, arg1, arg2);
					return true;
				}
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {e.printStackTrace();}
		}
	}
	
	arg0.sendMessage(CommandConstruct.getNoArgsMessage());
	
	return true;
}
 
Example 2
Project: OftenPorter   File: AnnoUtil.java   View Source Code Vote up 6 votes
private static boolean isAnnotationPresent(boolean isAll, Method method, Class<? extends Annotation>... annotationClasses)
{
    for (Class c : annotationClasses)
    {
        if (method.isAnnotationPresent(c))
        {
            if (!isAll)
            {
                return true;
            }
        } else if (isAll)
        {
            return false;
        }
    }
    return isAll;
}
 
Example 3
Project: J-Cord   File: EventManager.java   View Source Code Vote up 6 votes
/**
 * Register objects that have methods annotated as EventSubscriber.
 *
 * @param subscribers The subscribers object
 * @return EventManager for chaining.
 */
@SuppressWarnings("unchecked")
public EventManager registerEventSubscribers(Object... subscribers) {
    this.subscribers.addAll(Arrays.asList(subscribers));
    for (Object obj : subscribers) {
        for (Method method : obj.getClass().getMethods()) {
            if (method.isAnnotationPresent(EventSubscriber.class)) {
                Class<?>[] parameters = method.getParameterTypes();

                if (parameters.length == 1 && Event.class.isAssignableFrom(parameters[0])) {
                    Class<? extends Event> event = (Class<? extends Event>) parameters[0];
                    methods.put(method, new MethodContainer(obj, event));
                }
            }
        }
    }
    return this;
}
 
Example 4
Project: jedai-ui   File: WizardController.java   View Source Code Vote up 6 votes
private Method getMethod(Class<? extends Annotation> an, Object obj) {
    if (an == null) {
        return null;
    }

    if (obj == null) {
        return null;
    }

    Method[] methods = obj.getClass().getMethods();
    if (methods != null && methods.length > 0) {
        for (Method m : methods) {
            if (m.isAnnotationPresent(an)) {
                return m;
            }
        }
    }
    return null;
}
 
Example 5
Project: QiuQiu   File: MapperAspect.java   View Source Code Vote up 6 votes
@Around("mapperCheckPoint()")
private Object around(ProceedingJoinPoint point) throws Throwable {

    if(! check(point)) {
        return point.proceed();
    }
    if (! (point.getSignature() instanceof MethodSignature)) {
        return point.proceed();
    }

    MethodSignature methodSignature = (MethodSignature) point.getSignature();
    Method method = methodSignature.getMethod();
    if (! method.isAnnotationPresent(KeyParam.class)) {
        return point.proceed();
    }

    KeyParam keyParam = method.getAnnotation(KeyParam.class);
    String[] ognl = keyParam.value();
    String mapper = method.getDeclaringClass().getSimpleName() + "." + method.getName();
    RequestHolder.initRequestHolder(mapper, ognl);

    Object result = point.proceed();

    RequestHolder.resetRequest();
    return result;
}
 
Example 6
Project: vertx-zero   File: Answer.java   View Source Code Vote up 6 votes
private static <T> void storeSession(
        final RoutingContext context,
        final T data,
        final Method method
) {
    final Session session = context.session();
    if (null != session && null != data && method.isAnnotationPresent(SessionData.class)) {
        final Annotation annotation = method.getAnnotation(SessionData.class);
        final String key = Instance.invoke(annotation, "value");
        final String field = Instance.invoke(annotation, "field");
        // Data Storage
        Object reference = data;
        if (Types.isJObject(data) && StringUtil.notNil(field)) {
            final JsonObject target = (JsonObject) data;
            reference = target.getValue(field);
        }
        // Session Put
        session.put(key, reference);
    }
}
 
Example 7
Project: Mevius-IO   File: MeviusHandler.java   View Source Code Vote up 6 votes
public final void callEvent(PacketEvent event) {
	for (PacketListener listener : packetlisteners) {
		for (Method m : listener.getClass().getMethods()) {
			if (!m.isAnnotationPresent(PacketHandler.class))
				continue;
			if (m.getParameterTypes().length != 1)
				continue;
			Class<?> clazz = m.getParameterTypes()[0];
			if (!clazz.equals(event.getClass()) && !clazz.equals(PacketEvent.class))
				continue;
			PacketHandler ph = m.getAnnotation(PacketHandler.class);
			if (!ph.value().equals(event.getEventType()) && !ph.value().equals(PacketEventType.ALL))
				continue;
			try {
				m.setAccessible(true);
				m.invoke(listener, event);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
 
Example 8
Project: flowly   File: FlowRegister.java   View Source Code Vote up 5 votes
public <T> void register(Class<T> tClass){
    for(Method method : tClass.getDeclaredMethods()){
        if(method.isAnnotationPresent(FlowAction.class)){
            actions.add(new Action(tClass, method));
        }
    }
}
 
Example 9
Project: garlicts   File: ControllerAbility.java   View Source Code Vote up 5 votes
private static void handleActionMethod(Class<?> controllerClass, Method controllerMethod, Map<Requestor, Handler> commonControllerMap, Map<Requestor, Handler> regexpControllerMap) {
  	
  	// 判断当前 Action 方法是否带有 RequestMapping 注解
if (controllerMethod.isAnnotationPresent(RequestMapping.class)) {
	String requestPath = controllerMethod.getAnnotation(RequestMapping.class).value();
	RequestMethod requestMethod[] = controllerMethod.getAnnotation(RequestMapping.class).method();
	for(RequestMethod e : requestMethod){
		putActionMap(e.name(), requestPath, controllerClass, controllerMethod, commonControllerMap, regexpControllerMap);
	}
}
  	
  }
 
Example 10
Project: McLink   File: VItem.java   View Source Code Vote up 5 votes
public static Map<Item.ActionType, Method> getActions(Class<?> c) {
	Map<Item.ActionType, Method> a = new HashMap<Item.ActionType, Method>();
	
	for (Method m : c.getMethods()) {
		if (m.isAnnotationPresent(Item.Action.class)) {
			a.put(m.getAnnotation(Item.Action.class).type(), m);
		}
	}
	
	return a;
}
 
Example 11
Project: openjdk-jdk10   File: JavacParserTest.java   View Source Code Vote up 5 votes
void run(String[] args) throws Exception {
    int passed = 0, failed = 0;
    final Pattern p = (args != null && args.length > 0)
            ? Pattern.compile(args[0])
            : null;
    for (Method m : this.getClass().getDeclaredMethods()) {
        boolean selected = (p == null)
                ? m.isAnnotationPresent(Test.class)
                : p.matcher(m.getName()).matches();
        if (selected) {
            try {
                m.invoke(this, (Object[]) null);
                System.out.println(m.getName() + ": OK");
                passed++;
            } catch (Throwable ex) {
                System.out.printf("Test %s failed: %s %n", m, ex.getCause());
                failed++;
            }
        }
    }
    System.out.printf("Passed: %d, Failed %d%n", passed, failed);
    if (failed > 0) {
        throw new RuntimeException("Tests failed: " + failed);
    }
    if (passed == 0 && failed == 0) {
        throw new AssertionError("No test(s) selected: passed = " +
                passed + ", failed = " + failed + " ??????????");
    }
}
 
Example 12
Project: jwx   File: WeixinMethod.java   View Source Code Vote up 5 votes
/**
 * 判断方法是否有合法的微信注解
 * @param method
 * @return
 */
public static boolean hasWeixinAnnotationType(Method method){
	for(Class<? extends Annotation> at : weixinAnnotationTypes){
		if(method.isAnnotationPresent(at)){
			return true;
		}
	}
	
	return false;
}
 
Example 13
Project: Recaf   File: Bus.java   View Source Code Vote up 5 votes
/**
 * Check if method can listen to events,
 * 
 * @param method
 * @return
 */
private boolean isValid(Method method) {
	//@formatter:off
	return 
		// Check parameter for event type
		method.getParameterCount() == 1 && 
		Event.class.isAssignableFrom(method.getParameterTypes()[0]) && 
		// Check if listener annotation exists
		method.isAnnotationPresent(Listener.class);
	//@formatter:on
}
 
Example 14
Project: nifi-registry   File: AuthorizerFactory.java   View Source Code Vote up 5 votes
private void performMethodInjection(final Object instance, final Class authorizerClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    for (final Method method : authorizerClass.getMethods()) {
        if (method.isAnnotationPresent(AuthorizerContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);

            try {
                final Class<?>[] argumentTypes = method.getParameterTypes();

                // look for setters (single argument)
                if (argumentTypes.length == 1) {
                    final Class<?> argumentType = argumentTypes[0];

                    // look for well known types
                    if (NiFiRegistryProperties.class.isAssignableFrom(argumentType)) {
                        // nifi properties injection
                        method.invoke(instance, properties);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = authorizerClass.getSuperclass();
    if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}
 
Example 15
Project: datapipelines-java   File: AbstractDataTransformer.java   View Source Code Vote up 5 votes
private void initialize() {
    synchronized(initLock) {
        if(transformMethods != null) {
            return;
        }

        final Class<? extends AbstractDataTransformer> clazz = this.getClass();

        transformMethods = new HashMap<>();

        for(final Method method : clazz.getMethods()) {
            if(method.isAnnotationPresent(Transform.class)) {
                final Transform annotation = method.getAnnotation(Transform.class);

                Map<Class<?>, Method> from = transformMethods.get(annotation.from());
                if(from == null) {
                    from = new HashMap<>();
                    transformMethods.put(annotation.from(), from);
                }

                from.put(annotation.to(), method);
            }
        }

        transformMethods = Collections.unmodifiableMap(transformMethods);
    }
}
 
Example 16
Project: DovakinMQ   File: AnnotationFinder.java   View Source Code Vote up 5 votes
private static void buildConnectValidatorCache(Class<?> cls){
    Method[] methods = cls.getMethods();
    //ValidateNode node = new ValidateNode();
    List<Method> validateMethods = new ArrayList<Method>();
    for(Method method : methods){
        if(method.isAnnotationPresent(MqttValidate.class)){
            MqttValidate mqttValidate
                    = method.getAnnotation(MqttValidate.class);
            validateMethods.add(method);
        }
    }
}
 
Example 17
Project: alexa-skill   File: SpeechletConfiguration.java   View Source Code Vote up 5 votes
private SpeechletHandlerHolder buildHandler(String endpoint, List<Object> rawHandler) {
  SpeechletHandlerHolder holder = new SpeechletHandlerHolder();

  for(Object curRawHandler : rawHandler) {
    for(Method method : curRawHandler.getClass().getDeclaredMethods()) {
      if(method.isAnnotationPresent(OnLaunch.class)) {
        if(holder.onLaunch != null) {
          SpeechletHandler<OnLaunch> curHandler = new SpeechletHandler<>();
          curHandler.handler = curRawHandler;
          curHandler.method = method;

          throw new IllegalStateException("Multiple OnLaunch handler for endpoint '" + endpoint + "' found!\n\t" + holder.onLaunch + "\n\t" + curHandler);
        }

        holder.setOnLaunch(method, curRawHandler);
      } else if(method.isAnnotationPresent(OnSessionStarted.class)){
        holder.addSessionStarted(method, curRawHandler);
      } else if(method.isAnnotationPresent(OnSessionEnded.class)){
        holder.addSessionEnded(method, curRawHandler);
      } else if (method.isAnnotationPresent(OnIntent.class)) {
        holder.addOnIntent(method, curRawHandler);
      }
    }
  }

  return holder;
}
 
Example 18
Project: Samurai   File: AspectUtil.java   View Source Code Vote up 5 votes
public static boolean isAspectMethod(Method method) {
    if (method.isAnnotationPresent(Before.class)
            || method.isAnnotationPresent(After.class)
            || method.isAnnotationPresent(Around.class)) {
        return true;
    }
    return false;
}
 
Example 19
Project: CodeBroker   File: MBean.java   View Source Code Vote up 5 votes
private void scan() throws Exception {
    ManagedDescription descAnn = getClass().getAnnotation(ManagedDescription.class);
    if (descAnn != null) {
        description = descAnn.value();
    }

    for (Method method : getClass().getMethods()) {

        if (method.isAnnotationPresent(ManagedAnnotation.class)) {
            ManagedAnnotation ann = method.getAnnotation(ManagedAnnotation.class);
            String name = ann.value();
            if (name.isEmpty()) {
                throw new IllegalArgumentException("Name cannot be empty!");
            }
            boolean operation = ann.operation();
            HashMap<String, BeanInfo> map = operation ? operationMap : attributeMap;
            if (map.containsKey(name)) {
                throw new IllegalArgumentException("Duplicate name: " + name);
            }
            descAnn = method.getAnnotation(ManagedDescription.class);
            String desc = null;
            if (descAnn != null) {
                desc = descAnn.value();
            }
            map.put(name, new BeanInfo(name, desc, method));
        }
    }
}
 
Example 20
Project: gemoc-studio-modeldebugging   File: LaunchConfigurationMainTab.java   View Source Code Vote up 5 votes
protected String getModelInitializationMethodName(){
	String entryPointClassName = null;
	
	final String prefix = "public static void ";
	int startName = prefix.length();
	int endName = _entryPointMethodText.getText().lastIndexOf("(");
	if(endName == -1) return "";
	String entryMethod = _entryPointMethodText.getText().substring(startName, endName);
	int lastDot = entryMethod.lastIndexOf(".");
	if(lastDot != -1){
		entryPointClassName = entryMethod.substring(0, lastDot);
	}
	
	Bundle bundle = MelangeHelper.getMelangeBundle(_languageCombo.getText());
	
	if(entryPointClassName != null && bundle != null){
		try {
			Class<?> entryPointClass = bundle.loadClass(entryPointClassName);
			for(Method m : entryPointClass.getMethods()){
				// TODO find a better search mechanism (check signature, inheritance, aspects, etc)
				if(m.isAnnotationPresent(fr.inria.diverse.k3.al.annotationprocessor.InitializeModel.class)){
					return entryPointClassName+"."+m.getName();
				}
			}
		} catch (ClassNotFoundException e) {}
	}
		
	return "";
}