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

The following examples show how to use java.lang.reflect.Method#isAnnotationPresent() . 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 check out the related API usage on the sidebar.
Example 1
Source File: ArtHook.java    From ArtHook with 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
Source File: MethodFilterScanner.java    From seppuku with GNU General Public License v3.0 6 votes vote down vote up
@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 3
Source File: AdminPermissionUtil.java    From directory-fortress-core with Apache License 2.0 6 votes vote down vote up
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 4
Source File: InjectorImpl.java    From baratine with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 5
Source File: WebLogAspect.java    From xmall with 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 6
Source File: AbstractAnnotationHandler.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * 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 7
Source File: Kernel.java    From aparapi with 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 8
Source File: GraphTransactionAdvisor.java    From atlas with 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 9
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
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 File: JavaProperty.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static boolean isPk(Method readMethod) {
    if (isJPAClassAvaiable) {
        if (readMethod != null && readMethod.isAnnotationPresent(classForName("javax.persistence.Id"))) {
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: PermissionServiceImpl.java    From itweet-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 左边根菜单,初始化到权限资源表
 * @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
Source File: EventMethodReflection.java    From concursus with 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 13
Source File: CustomClassMapper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
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 File: AuthenticationInterceptor.java    From plumemo with Apache License 2.0 5 votes vote down vote up
@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 15
Source File: ClassFinder.java    From flow with 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 16
Source File: ViewDebug.java    From android_9.0.0_r45 with 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 17
Source File: AbstractTableViewer.java    From olca-app with Mozilla Public License 2.0 4 votes vote down vote up
private boolean supports(Class<? extends Annotation> clazz) {
	for (Method method : this.getClass().getDeclaredMethods())
		if (method.isAnnotationPresent(clazz))
			return true;
	return false;
}
 
Example 18
Source File: CallbackDescriptor.java    From deltaspike with 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 File: MethodDeclaration.java    From OpenPeripheral with 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
Source File: SpringJUnit4ClassRunner.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * 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()));
}