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

The following examples show how to use java.lang.reflect.Method#getAnnotation() . 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: NettySpring.java    From timer with Apache License 2.0 6 votes vote down vote up
public Object postProcessAfterInitialization(Object bean, String beanName) throws Exception {
    Object targetBean= AopTargetUtils.getTarget(bean);
    Class clazz =targetBean.getClass();

    Timer timer = (Timer) clazz.getAnnotation(Timer.class);
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        Clock clock = method.getAnnotation(Clock.class);
        if (clock != null) {
            NettyServerFactory.beanMapping.put(clazz.getName(), bean);
            if (timer.value() != null) {
                NettyServerFactory.beanMapping.put(timer.value(), bean);
            }

        }
    }
    return bean;
}
 
Example 2
Source File: RunTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
void run() throws Exception {
    for (Method m: getClass().getDeclaredMethods()) {
        Annotation a = m.getAnnotation(Test.class);
        if (a != null) {
            System.err.println("test: " + m.getName());
            try {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);;
                m.invoke(this, new Object[] { pw });
                String out = sw.toString();
                System.err.println(">>> " + out.replace("\n", "\n>>> "));
                if (!out.contains("a < b"))
                    error("\"a < b\" not found");
                if (!out.contains("a & b"))
                    error("\"a & b\" not found");
            } catch (InvocationTargetException e) {
                Throwable cause = e.getCause();
                throw (cause instanceof Exception) ? ((Exception) cause) : e;
            }
            System.err.println();
        }
    }

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example 3
Source File: PermissionUtils.java    From ReadMark with Apache License 2.0 6 votes vote down vote up
/**
 * 无需申请权限,直接找到请求码对应方法,执行。
 * @param mReflect
 * @param requestCode
 */
public static void executeSuccessMethod(Object mReflect, int requestCode) {
    // 获取所有方法
    Method[] methods = mReflect.getClass().getDeclaredMethods();
    // 找到标记成功的方法
    for(Method method : methods){
        PermissionSuccess sMethod = method.getAnnotation(PermissionSuccess.class);
        if(sMethod != null){
            int methodCode = sMethod.requestCode();
            //方法的注解里的请求码 和 传入参数的请求码相同,执行这个方法。
            if(methodCode == requestCode){
                executeMethod(mReflect, method);
            }
        }
    }
}
 
Example 4
Source File: KeyIndexesBuilder.java    From simple-spring-memcached with MIT License 6 votes vote down vote up
@Override
protected void build(final AnnotationData data, final Annotation annotation, final Class<? extends Annotation> expectedAnnotationClass,
        final Method targetMethod) {
    // Read*Cache annotations don't support ReturnValueKeyProvider, to cache method result cache keys must be
    // available before executing method.
    if (!isType(expectedAnnotationClass, Type.READ)) {
        final ReturnValueKeyProvider returnAnnotation = targetMethod.getAnnotation(ReturnValueKeyProvider.class);
        if (returnAnnotation != null) {
            data.setReturnKeyIndex(true);
            return;
        }
    }

    final boolean isMulti = isType(expectedAnnotationClass, Type.MULTI);
    final Collection<Integer> keyIndexes = getKeyIndexes(targetMethod, isMulti);
    if (keyIndexes.isEmpty()) {
        throw new InvalidParameterException(String.format("No KeyProvider annotation found method [%s]", targetMethod.getName()));
    }

    data.setKeyIndexes(keyIndexes);
}
 
Example 5
Source File: FactExtensions.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies if the given function is marked as pure or its names is considered as pure.
 * This function does not test the purity of the associated code.
 *
 * @param type the type in which the function is declared.
 * @param name the name of the function.
 * @param parameters the type of the arguments.
 * @return {@code true} if the function is pure.
 * @throws SecurityException if the function declaration cannot be accessed.
 * @throws NoSuchMethodException if the function cannot be found.
 * @since 0.12
 */
public static boolean isPureFunctionPrototype(Class<?> type, String name, Class<?>... parameters) {
	Method method;
	try {
		method = type.getDeclaredMethod(name, parameters);
	} catch (NoSuchMethodException | SecurityException e) {
		return false;
	}
	if (method.getAnnotation(Pure.class) != null) {
		return true;
	}
	if (getOperationNameValidator().isNamePatternForNotPureOperation(method.getName())) {
		return false;
	}
	return getOperationNameValidator().isNamePatternForPureOperation(method.getName());
}
 
Example 6
Source File: WebLogAspect.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    //获取当前请求对象
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //记录请求信息
    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 apiOperation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(apiOperation.value());
    }
    long endTime = System.currentTimeMillis();
    String urlStr = request.getRequestURL().toString();
    webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
    webLog.setIp(request.getRemoteUser());
    webLog.setMethod(request.getMethod());
    webLog.setParameter(getParameter(method, joinPoint.getArgs()));
    webLog.setResult(result);
    webLog.setSpendTime((int) (endTime - startTime));
    webLog.setStartTime(startTime);
    webLog.setUri(request.getRequestURI());
    webLog.setUrl(request.getRequestURL().toString());
    LOGGER.info("{}", JSONUtil.parse(webLog));
    return result;
}
 
Example 7
Source File: MessagesInvoker.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
protected String getAnnotationPattern(final Method method ) {
  String pattern = null;
  Message anno = method.getAnnotation( Message.class );
  if( anno != null ) {
    pattern = anno.text();
  }
  return pattern;
}
 
Example 8
Source File: DefaultSetterFactoryTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateCommandKey() {
    for (Method method : TestCase.class.getMethods()) {
        if (method.isAnnotationPresent(HystrixCommandKey.class)) {
            HystrixCommandKey annotation = method.getAnnotation(HystrixCommandKey.class);
            Assert.assertEquals(annotation.value(), DefaultSetterFactory.generateCommandKey("TestCase", method));
        }
    }
}
 
Example 9
Source File: AspectjAopInterceptor.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
public void checkAndDeleteCache(JoinPoint jp, Object retVal) throws Throwable {
    Signature signature = jp.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(CacheDelete.class)) {
        CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class);
        this.deleteCache(jp, cacheDelete, retVal);
    }
}
 
Example 10
Source File: MCRJerseyDefaultFeature.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
protected void registerAccessFilter(FeatureContext context, Class<?> resourceClass, Method resourceMethod) {
    MCRRestrictedAccess restrictedAccessMETHOD = resourceMethod.getAnnotation(MCRRestrictedAccess.class);
    MCRRestrictedAccess restrictedAccessTYPE = resourceClass.getAnnotation(MCRRestrictedAccess.class);
    if (restrictedAccessMETHOD != null) {
        LOGGER.info("Access to {} is restricted by {}", resourceMethod,
            restrictedAccessMETHOD.value().getCanonicalName());
        addFilter(context, restrictedAccessMETHOD);
    } else if (restrictedAccessTYPE != null) {
        LOGGER.info("Access to {} is restricted by {}", resourceClass.getName(),
            restrictedAccessTYPE.value().getCanonicalName());
        addFilter(context, restrictedAccessTYPE);
    }
}
 
Example 11
Source File: MarshallerBase.java    From marshalsec with MIT License 5 votes vote down vote up
private void runAll ( boolean test, boolean verbose, boolean throwEx, EscapeType escape ) throws Exception {

        for ( GadgetType t : this.getSupportedTypes() ) {
            Method tm = getTargetMethod(t);
            Args a = tm.getAnnotation(Args.class);
            if ( a == null ) {
                throw new Exception("Missing Args in " + t);
            }
            if ( a.noTest() ) {
                continue;
            }
            String[] defaultArgs = a.defaultArgs();
            doRun(t, test, verbose, throwEx, escape, defaultArgs);
        }
    }
 
Example 12
Source File: JvmModelGeneratorTest.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBug419430() {
  try {
    final XExpression expression = this.expression("null");
    final JvmAnnotationReferenceBuilder jvmAnnotationReferenceBuilder = this.jvmAnnotationReferenceBuilderFactory.create(expression.eResource().getResourceSet());
    final Procedure1<JvmGenericType> _function = (JvmGenericType it) -> {
      EList<JvmMember> _members = it.getMembers();
      final Procedure1<JvmOperation> _function_1 = (JvmOperation it_1) -> {
        this.builder.setBody(it_1, expression);
        final JvmAnnotationReference annotation = jvmAnnotationReferenceBuilder.annotationRef(TestAnnotations.class);
        final JvmAnnotationAnnotationValue annotationAnnotationValue = this.typesFactory.createJvmAnnotationAnnotationValue();
        EList<JvmAnnotationReference> _values = annotationAnnotationValue.getValues();
        JvmAnnotationReference _annotationRef = jvmAnnotationReferenceBuilder.annotationRef(TestAnnotation.class);
        this.builder.<JvmAnnotationReference>operator_add(_values, _annotationRef);
        EList<JvmAnnotationReference> _values_1 = annotationAnnotationValue.getValues();
        JvmAnnotationReference _annotationRef_1 = jvmAnnotationReferenceBuilder.annotationRef(TestAnnotation.class);
        this.builder.<JvmAnnotationReference>operator_add(_values_1, _annotationRef_1);
        EList<JvmAnnotationReference> _values_2 = annotationAnnotationValue.getValues();
        JvmAnnotationReference _annotationRef_2 = jvmAnnotationReferenceBuilder.annotationRef(TestAnnotation.class);
        this.builder.<JvmAnnotationReference>operator_add(_values_2, _annotationRef_2);
        EList<JvmAnnotationValue> _explicitValues = annotation.getExplicitValues();
        this.builder.<JvmAnnotationAnnotationValue>operator_add(_explicitValues, annotationAnnotationValue);
        EList<JvmAnnotationReference> _annotations = it_1.getAnnotations();
        this.builder.<JvmAnnotationReference>operator_add(_annotations, annotation);
      };
      JvmOperation _method = this.builder.toMethod(expression, "doStuff", this.references.getTypeForName("java.lang.Object", expression), _function_1);
      this.builder.<JvmOperation>operator_add(_members, _method);
    };
    final JvmGenericType clazz = this.builder.toClass(expression, "my.test.Foo", _function);
    final String code = this.generate(expression.eResource(), clazz);
    Assert.assertTrue(code, code.contains("@TestAnnotations({ @TestAnnotation, @TestAnnotation, @TestAnnotation })"));
    final Class<?> compiledClazz = this.compileToClass(expression.eResource(), clazz, code);
    final Method method = compiledClazz.getMethod("doStuff");
    final TestAnnotations methodAnnotation = method.<TestAnnotations>getAnnotation(TestAnnotations.class);
    Assert.assertEquals(3, ((List<TestAnnotation>)Conversions.doWrapArray(methodAnnotation.value())).size());
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 13
Source File: EntityManagerProducer.java    From BeanTest with Apache License 2.0 5 votes vote down vote up
@Produces
public EntityManager getEntityManager(InjectionPoint ip) {
    PersistenceContext ctx = ip.getAnnotated().getAnnotation(PersistenceContext.class);
    
    if (ctx == null) {
    	//if @PersisteceContext is declared on method, ctx is null at this point.
    	//ctx should be retrieved from the Method.
    	Member member = ip.getMember();
    	if (member instanceof Method) {
    		Method method = (Method) member;
    		ctx = method.getAnnotation(PersistenceContext.class);
    	}
    }
    
    LOGGER.debug("PersistenceContext info:");
    //This could happen if the application injects the EntityManager via @Inject instead of @PersistenceContext
    if(ctx != null) {
        LOGGER.debug("Unit name: {}", ctx.unitName());
    }
    
    LOGGER.debug("Bean defining the injection point: {}", ip.getBean().getBeanClass());
    LOGGER.debug("Field to be injected: {}", ip.getMember());

    if (em == null) {
        em = emf.createEntityManager();
    }
    return em;
}
 
Example 14
Source File: MapToBeanConvertor.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected <A extends Annotation> Optional<A> findAnnotation(Class<A> annoClass){
	Method method = propertyDescriptor.getReadMethod();
	A fn = null;
	if(method==null || (fn = method.getAnnotation(annoClass))==null){
		Field field = ReflectUtils.getIntro(getBeanClass()).getField(propertyDescriptor.getName());
		if(field!=null){
			fn = field.getAnnotation(annoClass);
		}
	}
	return Optional.ofNullable(fn);
}
 
Example 15
Source File: SimpleDbQueryMethod.java    From spring-data-simpledb with MIT License 4 votes vote down vote up
public static boolean isAnnotatedQuery(final Method method) {
	return method.getAnnotation(Query.class) != null;
}
 
Example 16
Source File: JaxWsServiceConfiguration.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> getRequestWrapper(Method selected) {
    if (this.requestMethodClassNotFoundCache.contains(selected)) {
        return null;
    }
    Class<?> cachedClass = requestMethodClassCache.get(selected);
    if (cachedClass != null) {
        return cachedClass;
    }

    Method m = getDeclaredMethod(selected);

    RequestWrapper rw = m.getAnnotation(RequestWrapper.class);
    String clsName = "";
    if (rw == null) {
        clsName = getPackageName(selected) + ".jaxws." + StringUtils.capitalize(selected.getName());
    } else {
        clsName = rw.className();
    }

    if (clsName.length() > 0) {
        cachedClass = requestMethodClassCache.get(clsName);
        if (cachedClass != null) {
            requestMethodClassCache.put(selected, cachedClass);
            return cachedClass;
        }
        try {
            Class<?> r = ClassLoaderUtils.loadClass(clsName, implInfo.getEndpointClass());
            requestMethodClassCache.put(clsName, r);
            requestMethodClassCache.put(selected, r);
            if (m.getParameterTypes().length == 1 && r.equals(m.getParameterTypes()[0])) {
                LOG.log(Level.WARNING, "INVALID_REQUEST_WRAPPER", new Object[] {clsName,
                        m.getParameterTypes()[0].getName()});
            }
            return r;
        } catch (ClassNotFoundException e) {
            //do nothing, we will mock a schema for wrapper bean later on
        }
    }
    requestMethodClassNotFoundCache.add(selected);
    return null;
}
 
Example 17
Source File: AnnotationUtils.java    From cxf with Apache License 2.0 4 votes vote down vote up
public static <A extends Annotation> A getMethodAnnotation(Method m, Class<A> aClass) {
    return m == null ? null : m.getAnnotation(aClass);
}
 
Example 18
Source File: AnnotationTypeMapping.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private Method resolveAliasTarget(Method attribute, AliasFor aliasFor, boolean checkAliasPair) {
	if (StringUtils.hasText(aliasFor.value()) && StringUtils.hasText(aliasFor.attribute())) {
		throw new AnnotationConfigurationException(String.format(
				"In @AliasFor declared on %s, attribute 'attribute' and its alias 'value' " +
				"are present with values of '%s' and '%s', but only one is permitted.",
				AttributeMethods.describe(attribute), aliasFor.attribute(),
				aliasFor.value()));
	}
	Class<? extends Annotation> targetAnnotation = aliasFor.annotation();
	if (targetAnnotation == Annotation.class) {
		targetAnnotation = this.annotationType;
	}
	String targetAttributeName = aliasFor.attribute();
	if (!StringUtils.hasLength(targetAttributeName)) {
		targetAttributeName = aliasFor.value();
	}
	if (!StringUtils.hasLength(targetAttributeName)) {
		targetAttributeName = attribute.getName();
	}
	Method target = AttributeMethods.forAnnotationType(targetAnnotation).get(targetAttributeName);
	if (target == null) {
		if (targetAnnotation == this.annotationType) {
			throw new AnnotationConfigurationException(String.format(
					"@AliasFor declaration on %s declares an alias for '%s' which is not present.",
					AttributeMethods.describe(attribute), targetAttributeName));
		}
		throw new AnnotationConfigurationException(String.format(
				"%s is declared as an @AliasFor nonexistent %s.",
				StringUtils.capitalize(AttributeMethods.describe(attribute)),
				AttributeMethods.describe(targetAnnotation, targetAttributeName)));
	}
	if (target == attribute) {
		throw new AnnotationConfigurationException(String.format(
				"@AliasFor declaration on %s points to itself. " +
				"Specify 'annotation' to point to a same-named attribute on a meta-annotation.",
				AttributeMethods.describe(attribute)));
	}
	if (!isCompatibleReturnType(attribute.getReturnType(), target.getReturnType())) {
		throw new AnnotationConfigurationException(String.format(
				"Misconfigured aliases: %s and %s must declare the same return type.",
				AttributeMethods.describe(attribute),
				AttributeMethods.describe(target)));
	}
	if (isAliasPair(target) && checkAliasPair) {
		AliasFor targetAliasFor = target.getAnnotation(AliasFor.class);
		if (targetAliasFor == null) {
			throw new AnnotationConfigurationException(String.format(
					"%s must be declared as an @AliasFor '%s'.",
					StringUtils.capitalize(AttributeMethods.describe(target)),
					attribute.getName()));
		}
		Method mirror = resolveAliasTarget(target, targetAliasFor, false);
		if (mirror != attribute) {
			throw new AnnotationConfigurationException(String.format(
					"%s must be declared as an @AliasFor '%s', not '%s'.",
					StringUtils.capitalize(AttributeMethods.describe(target)),
					attribute.getName(), mirror.getName()));
		}
	}
	return target;
}
 
Example 19
Source File: AbstractClassGenerator.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void addGetter(Method method) {
    if (getters.add(method) && method.getAnnotation(Inject.class) != null) {
        injector = true;
    }
}
 
Example 20
Source File: ReflectExtensions.java    From sarl with Apache License 2.0 4 votes vote down vote up
private static boolean isDeprecated(Method method) {
	return Flags.isDeprecated(method.getModifiers()) || method.getAnnotation(Deprecated.class) != null;
}