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

The following examples show how to use java.lang.reflect.Method#isAnnotationPresent() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: ArtHook   File: ArtHook.java    License: Apache License 2.0 6 votes vote down vote up
public static OriginalMethod hook(Method method) {
    if (!method.isAnnotationPresent(Hook.class))
        throw new IllegalArgumentException("method must have @Hook annotation");

    Object original;
    try {
        original = findTargetMethod(method);
    } catch (Throwable e) {
        throw new RuntimeException("Can't find original method (" + method.getName() + ")", e);
    }
    String ident = null;
    if (method.isAnnotationPresent(BackupIdentifier.class)) {
        ident = method.getAnnotation(BackupIdentifier.class).value();
    }
    return hook(original, method, ident);
}
 
Example 2
private static List<String> getOperations(Class clazz)
{
    List<String> operations = new ArrayList<String>();

    final Method[] declaredMethods = clazz.getDeclaredMethods();
    for ( final Method method : declaredMethods )
    {
        if ( method.isAnnotationPresent( AdminPermissionOperation.class ) )
        {
            AdminPermissionOperation annotation = method.getAnnotation( AdminPermissionOperation.class );
            if ( annotation.operationName() != null && !annotation.operationName().isEmpty() )
            {
                operations.add( annotation.operationName() );
            }
            else
            {
                operations.add( method.getName() );
            }
        }
    }

    return operations;
}
 
Example 3
/**
 * Introspect for @PostConstruct methods.
 */
//@Override
private void introspectInit(List<InjectProgram> program, Class<?> type)
{
  if (type == null) {
    return;
  }

  introspectInit(program, type.getSuperclass());

  try {
    for (Method method : type.getDeclaredMethods()) {
      if (method.isAnnotationPresent(PostConstruct.class)) {
        // XXX: program.add(new PostConstructProgram(Config.getCurrent(), method));
      }
    }
  } catch (Throwable e) {
    log.log(Level.FINEST, e.toString(), e);
  }
}
 
Example 4
@Override
public Set<EventFilter> scan(final Method listener) {
    if (!listener.isAnnotationPresent(Listener.class))
        return Collections.emptySet();

    final Set<EventFilter> filters = new HashSet<>();
    // iterate all filters in the annotation and instantiate them
    for (final Class<? extends EventFilter> filter : listener
            .getDeclaredAnnotation(Listener.class).filters())
        try {
            filters.add(filter.newInstance());
        } catch (final Exception exception) {
            exception.printStackTrace();
        }

    return filters;
}
 
Example 5
Source Project: android_9.0.0_r45   File: ViewDebug.java    License: Apache License 2.0 5 votes vote down vote up
private static Method[] capturedViewGetPropertyMethods(Class<?> klass) {
    if (mCapturedViewMethodsForClasses == null) {
        mCapturedViewMethodsForClasses = new HashMap<Class<?>, Method[]>();
    }
    final HashMap<Class<?>, Method[]> map = mCapturedViewMethodsForClasses;

    Method[] methods = map.get(klass);
    if (methods != null) {
        return methods;
    }

    final ArrayList<Method> foundMethods = new ArrayList<Method>();
    methods = klass.getMethods();

    int count = methods.length;
    for (int i = 0; i < count; i++) {
        final Method method = methods[i];
        if (method.getParameterTypes().length == 0 &&
                method.isAnnotationPresent(CapturedViewProperty.class) &&
                method.getReturnType() != Void.class) {
            method.setAccessible(true);
            foundMethods.add(method);
        }
    }

    methods = foundMethods.toArray(new Method[foundMethods.size()]);
    map.put(klass, methods);

    return methods;
}
 
Example 6
Source Project: xmall   File: WebLogAspect.java    License: MIT License 5 votes vote down vote up
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    //获取当前请求对象
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //记录请求信息(通过logstash传入elasticsearch)
    WebLog webLog = new WebLog();
    Object result = joinPoint.proceed();
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(ApiOperation.class)) {
        ApiOperation log = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(log.value());
    }
    long endTime = System.currentTimeMillis();
    webLog.setBasePath(RequestUtil.getBasePath(request));
    webLog.setIp(request.getRemoteUser());
    webLog.setMethod(request.getMethod());
    webLog.setParameter(getParameter(method, joinPoint.getArgs()));
    webLog.setResult(result);
    webLog.setSpendTime((int) (endTime - startTime.get()));
    webLog.setStartTime(startTime.get());
    webLog.setUri(request.getRequestURI());
    webLog.setUrl(request.getRequestURL().toString());
    Map<String,Object> logMap = new HashMap<>();
    logMap.put("url",webLog.getUrl());
    logMap.put("method",webLog.getMethod());
    logMap.put("parameter",webLog.getParameter());
    logMap.put("spendTime",webLog.getSpendTime());
    logMap.put("description",webLog.getDescription());
    //        LOGGER.info("{}", JsonUtil.objectToJson(webLog));
    LOGGER.info(Markers.appendEntries(logMap),JsonUtil.objectToJson(webLog));
    return result;
}
 
Example 7
Source Project: flow   File: ClassFinder.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean isTestClass(Class<?> cls) {
    if (cls.getEnclosingClass() != null
            && isTestClass(cls.getEnclosingClass())) {
        return true;
    }

    // Test classes with a @Test annotation on some method
    for (Method method : cls.getMethods()) {
        if (method.isAnnotationPresent(Test.class)) {
            return true;
        }
    }

    return false;
}
 
Example 8
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
    // 从 http 请求头中取出 token
    String token = httpServletRequest.getHeader(Constants.AUTHENTICATION);

    // 如果不是映射到方法直接通过
    if (!(object instanceof HandlerMethod)) {
        return true;
    }
    HandlerMethod handlerMethod = (HandlerMethod) object;
    Method method = handlerMethod.getMethod();
    //检查是否有LoginRequired注释,没有有则跳过认证
    if (!method.isAnnotationPresent(LoginRequired.class)) {
        return true;
    }

    LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
    if (loginRequired.required()) {
        // 执行认证
        if (token == null) {
            ExceptionUtil.rollback(ErrorEnum.INVALID_TOKEN);
        }

        RoleEnum role = loginRequired.role();
        if (role == RoleEnum.USER) {
            return true;
        }

        if (role == RoleEnum.ADMIN) {
            UserSessionVO userSessionInfo = SessionUtil.getUserSessionInfo();
            if (role != RoleEnum.getEnumTypeMap().get(userSessionInfo.getRoleId())) {
                ExceptionUtil.rollback(ErrorEnum.ACCESS_NO_PRIVILEGE);
            }
        }

        return true;
    }

    return true;
}
 
Example 9
private static boolean shouldIncludeGetter(Method method) {
  if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) {
    return false;
  }
  // Exclude methods from Object.class
  if (method.getDeclaringClass().equals(Object.class)) {
    return false;
  }
  // Non-public methods
  if (!Modifier.isPublic(method.getModifiers())) {
    return false;
  }
  // Static methods
  if (Modifier.isStatic(method.getModifiers())) {
    return false;
  }
  // No return type
  if (method.getReturnType().equals(Void.TYPE)) {
    return false;
  }
  // Non-zero parameters
  if (method.getParameterTypes().length != 0) {
    return false;
  }
  // Excluded methods
  if (method.isAnnotationPresent(Exclude.class)) {
    return false;
  }
  return true;
}
 
Example 10
Source Project: concursus   File: EventMethodReflection.java    License: MIT License 5 votes vote down vote up
public static int getCharacteristics(Method method) {
    return method.isAnnotationPresent(Initial.class)
            ? EventCharacteristics.IS_INITIAL
            : method.isAnnotationPresent(Terminal.class)
                ? EventCharacteristics.IS_TERMINAL
                : 0;
}
 
Example 11
/**
 * 左边根菜单,初始化到权限资源表
 * @param c
 * @return
 */
private void RootMenu(Class c) {
    String path = null;
    if(c.isAnnotationPresent(RequestMapping.class)) {
        path = ((RequestMapping)c.getAnnotation(RequestMapping.class)).value()[0];
    }
    Method[] ms = c.getDeclaredMethods();
    List<SysPermission> list = new ArrayList<>();
    SysPermission mr = null;
    for (Method m : ms) {
        //添加left菜单
        if (m.isAnnotationPresent(RootMenu.class)) {
            String url = null;
            if (m.isAnnotationPresent(GetMapping.class)) {
                url = path + ((GetMapping)m.getAnnotation(GetMapping.class)).value()[0];
            }
            if (m.isAnnotationPresent(PostMapping.class)) {
                url = path + ((PostMapping)m.getAnnotation(PostMapping.class)).value()[0];
            }
            if (m.isAnnotationPresent(PutMapping.class)) {
                url = path + ((PutMapping)m.getAnnotation(PutMapping.class)).value()[0];
            }
            if (m.isAnnotationPresent(DeleteMapping.class)) {
                url = path + ((DeleteMapping)m.getAnnotation(DeleteMapping.class)).value()[0];
            }
            RootMenu nm = m.getAnnotation(RootMenu.class);
            mr = new SysPermission();
            mr.setPname(nm.pname());
            mr.setPid(Integer.valueOf(nm.pid()));
            mr.setUrl(nm.url());
            mr.setDescritpion(nm.descritpion());
            mr.setName(nm.name());
            mr.setOperation(nm.operation());
            list.add(mr);
        }
    }
    if (list.size() <= 0)
        new SystemException("初始化权限失败,需要初始化的权限集合不能为空!");
    permissionRepository.save(list);
}
 
Example 12
public static boolean isPk(Method readMethod) {
    if (isJPAClassAvaiable) {
        if (readMethod != null && readMethod.isAnnotationPresent(classForName("javax.persistence.Id"))) {
            return true;
        }
    }
    return false;
}
 
Example 13
private static boolean shouldIncludeGetter(Method method) {
  if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) {
    return false;
  }
  // Exclude methods from Object.class
  if (method.getDeclaringClass().equals(Object.class)) {
    return false;
  }
  // Non-public methods
  if (!Modifier.isPublic(method.getModifiers())) {
    return false;
  }
  // Static methods
  if (Modifier.isStatic(method.getModifiers())) {
    return false;
  }
  // No return type
  if (method.getReturnType().equals(Void.TYPE)) {
    return false;
  }
  // Non-zero parameters
  if (method.getParameterTypes().length != 0) {
    return false;
  }
  // Excluded methods
  if (method.isAnnotationPresent(Exclude.class)) {
    return false;
  }
  return true;
}
 
Example 14
Source Project: atlas   File: GraphTransactionAdvisor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(Method method, Class<?> targetClass) {
    boolean annotationPresent = method.isAnnotationPresent(GraphTransaction.class);
    if (annotationPresent) {
        LOG.info("GraphTransaction intercept for {}.{}", targetClass.getName(), method.getName());
    }
    return annotationPresent;
}
 
Example 15
Source Project: aparapi   File: Kernel.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isMappedMethod(MethodReferenceEntry methodReferenceEntry) {
   if (CacheEnabler.areCachesEnabled())
      return getBoolean(mappedMethodFlags, methodReferenceEntry);
   boolean isMapped = false;
   for (final Method kernelMethod : Kernel.class.getDeclaredMethods()) {
      if (kernelMethod.isAnnotationPresent(OpenCLMapping.class)) {
         if (methodReferenceEntry.getNameAndTypeEntry().getNameUTF8Entry().getUTF8().equals(kernelMethod.getName())) {

            // well they have the same name ;)
            isMapped = true;
         }
      }
   }
   return (isMapped);
}
 
Example 16
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param method
 * @return String
 * @throws InitializationException <br>
 */
protected String cacheSqlTemplate(final Method method) throws InitializationException {
    String key = CacheHelper.buildKey(method.getDeclaringClass().getName(), BeanUtil.getMethodSignature(method));
    String templateSql = null;
    try {
        templateSql = daoConfig.isCache() ? CacheHelper.getCache().get(CacheConstant.SQL_DIR, key) : null;
        if (StringUtils.isEmpty(templateSql)) {
            String path = null;

            // 获取方法的SQL标签
            if (method.isAnnotationPresent(Sql.class)) {
                Sql sql = method.getAnnotation(Sql.class);
                templateSql = sql.value();
                path = sql.path();
            }

            if (StringUtils.isEmpty(templateSql)) {
                templateSql = checkSqlPath(method, path);
            }
            if (daoConfig.isCache()) {
                CacheHelper.getCache().put(CacheConstant.SQL_DIR, key, templateSql);
            }
        }
    }
    catch (Exception e) {
        throw new InitializationException(ErrorCodeDef.CACHE_ERROR_10002, e);
    }
    return StringUtils.trim(templateSql);
}
 
Example 17
private boolean supports(Class<? extends Annotation> clazz) {
	for (Method method : this.getClass().getDeclaredMethods())
		if (method.isAnnotationPresent(clazz))
			return true;
	return false;
}
 
Example 18
Source Project: deltaspike   File: CallbackDescriptor.java    License: Apache License 2.0 4 votes vote down vote up
private void findMethodWithCallbackMarker(Class<? extends Annotation> callbackMarker,
                                          Class<?> classToAnalyze,
                                          List<String> processedMethodNames)
{
    Class<?> currentClass = classToAnalyze;

    while (currentClass != null && !Object.class.getName().equals(currentClass.getName()))
    {
        for (Method currentMethod : currentClass.getDeclaredMethods())
        {
            //don't process overridden methods
            //ds now allows callbacks with parameters -> TODO refactor this approach
            if (processedMethodNames.contains(currentMethod.getName()))
            {
                continue;
            }

            if (currentMethod.isAnnotationPresent(callbackMarker))
            {
                processedMethodNames.add(currentMethod.getName());

                if (Modifier.isPrivate(currentMethod.getModifiers()))
                {
                    throw new IllegalStateException(
                        "Private methods aren't supported to avoid side-effects with normal-scoped CDI beans." +
                            " Please use e.g. protected or public instead. ");
                }

                currentMethod.setAccessible(true);
                this.callbackMethods.add(currentMethod);
            }
        }

        //scan interfaces
        for (Class<?> interfaceClass : currentClass.getInterfaces())
        {
            findMethodWithCallbackMarker(callbackMarker, interfaceClass, processedMethodNames);
        }

        currentClass = currentClass.getSuperclass();
    }
}
 
Example 19
Source Project: OpenPeripheral   File: MethodDeclaration.java    License: MIT License 4 votes vote down vote up
public MethodDeclaration(Class<?> rootClass, Method method, ScriptCallable meta, String source) {
	this.method = method;
	this.source = source;

	this.names = getNames(method, meta);

	this.description = meta.description();
	this.returnTypes = ImmutableList.copyOf(meta.returnTypes());
	this.validateReturn = meta.validateReturn();

	this.multipleReturn = method.isAnnotationPresent(MultipleReturn.class);

	this.wrappedReturn = TypeHelper.createFromReturn(returnTypes);

	if (validateReturn) validateResultCount();

	final Type methodArgs[] = method.getGenericParameterTypes();
	final boolean isVarArg = method.isVarArgs();

	ArgParseState state = ArgParseState.ENV_UNNAMED;

	TypeToken<?> scopeType = TypeToken.of(rootClass);

	final Annotation[][] argsAnnotations = method.getParameterAnnotations();
	for (int argIndex = 0; argIndex < methodArgs.length; argIndex++) {
		try {
			final TypeToken<?> argType = scopeType.resolveType(methodArgs[argIndex]);

			AnnotationMap argAnnotations = new AnnotationMap(argsAnnotations[argIndex]);

			boolean optionalStart = argAnnotations.get(Optionals.class) != null;

			Env envArg = argAnnotations.get(Env.class);
			Arg luaArg = argAnnotations.get(Arg.class);

			Preconditions.checkState(envArg == null || luaArg == null, "@Arg and @Env are mutually exclusive");
			if (luaArg != null) {

				if (state != ArgParseState.ARG_OPTIONAL) state = ArgParseState.ARG_REQUIRED;

				if (optionalStart) {
					Preconditions.checkState(state != ArgParseState.ENV_NAMED, "@Optional used more than once");
					state = ArgParseState.ARG_OPTIONAL;
				}

				boolean isLastArg = argIndex == (methodArgs.length - 1);

				ArgumentBuilder builder = new ArgumentBuilder();
				builder.setVararg(isLastArg && isVarArg);
				builder.setOptional(state == ArgParseState.ARG_OPTIONAL);
				builder.setNullable(luaArg.isNullable());

				final Argument arg = builder.build(luaArg.name(), luaArg.description(), luaArg.type(), argType, argIndex);
				callArgs.add(arg);
			} else {
				Preconditions.checkState(state == ArgParseState.ENV_NAMED || state == ArgParseState.ENV_UNNAMED, "Unannotated arg in script part (perhaps missing @Arg annotation?)");
				Preconditions.checkState(!optionalStart, "@Optionals does not work for env arguments");

				Class<?> rawArgType = argType.getRawType();
				if (envArg != null) {
					Preconditions.checkState(state == ArgParseState.ENV_NAMED || state == ArgParseState.ENV_UNNAMED, "@Env annotation used in script part of arguments");
					final String envName = envArg.value();
					EnvArg prev = envArgs.put(envName, new EnvArg(rawArgType, argIndex));
					if (prev != null) { throw new IllegalStateException(String.format("Conflict on name %s, args: %s, %s", envArg, prev.index, argIndex)); }
					state = ArgParseState.ENV_NAMED;
				} else {
					Preconditions.checkState(state == ArgParseState.ENV_UNNAMED, "Unnamed env cannot occur after named");
					unnamedEnvArg.put(argIndex, rawArgType);
				}
			}
		} catch (Throwable t) {
			throw new ArgumentDefinitionException(argIndex, t);
		}
	}

	this.argCount = unnamedEnvArg.size() + envArgs.size() + callArgs.size();
	Preconditions.checkState(this.argCount == methodArgs.length, "Internal error for method %s", method);
}
 
Example 20
/**
 * Return {@code true} if {@link Ignore @Ignore} is present for the supplied
 * {@linkplain FrameworkMethod test method} or if the test method is disabled
 * via {@code @IfProfileValue}.
 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Method, Class)
 */
protected boolean isTestMethodIgnored(FrameworkMethod frameworkMethod) {
	Method method = frameworkMethod.getMethod();
	return (method.isAnnotationPresent(Ignore.class) ||
			!ProfileValueUtils.isTestEnabledInThisEnvironment(method, getTestClass().getJavaClass()));
}