Java Code Examples for java.lang.reflect.Method#getDeclaredAnnotation()
The following examples show how to use
java.lang.reflect.Method#getDeclaredAnnotation() .
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 check out the related API usage on the sidebar.
Example 1
Source Project: vert.x-microservice File: ServiceVerticle.java License: Apache License 2.0 | 6 votes |
private Object[] invokeObjectEBParameters(Message<Object> m, Method method) { final java.lang.reflect.Parameter[] parameters = method.getParameters(); final Object[] parameterResult = new Object[parameters.length]; final Consumes consumes = method.getDeclaredAnnotation(Consumes.class); int counter = 0; for (java.lang.reflect.Parameter p : parameters) { if (p.getType().equals(EBMessageReply.class)) { final String consumesVal = consumes != null && consumes.value().length > 0 ? consumes.value()[0] : ""; parameterResult[counter] = new EBMessageReply(this.vertx.eventBus(), m, consumesVal, getConverter()); } else { if (TypeTool.isCompatibleType(p.getType())) { parameterResult[counter] = p.getType().cast(m.body()); } else { parameterResult[counter] = getConverter().convertToObject(String.valueOf(m.body()), p.getType()); } } counter++; } return parameterResult; }
Example 2
Source Project: vert.x-microservice File: ServiceVerticle.java License: Apache License 2.0 | 6 votes |
private Object[] invokeWSParameters(Message<byte[]> m, Method method) { final WSDataWrapper wrapper = getWSDataWrapper(m); final java.lang.reflect.Parameter[] parameters = method.getParameters(); final Object[] parameterResult = new Object[parameters.length]; final Consumes consumes = method.getDeclaredAnnotation(Consumes.class); int i = 0; for (java.lang.reflect.Parameter p : parameters) { if (p.getType().equals(WSMessageReply.class)) { parameterResult[i] = new WSMessageReply(wrapper.getEndpoint(), this.vertx.eventBus(), this.getConfig()); } else { putTypedWSParameter(consumes, parameterResult, p, i, wrapper.getData()); } i++; } return parameterResult; }
Example 3
Source Project: beihu-boot File: ApiBootDataSourceSwitchAnnotationInterceptor.java License: Apache License 2.0 | 6 votes |
@Override public Object invoke(MethodInvocation invocation) throws Throwable { try { Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null); Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass); Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); // get class declared DataSourceSwitch annotation DataSourceSwitch dataSourceSwitch = targetClass.getDeclaredAnnotation(DataSourceSwitch.class); if (dataSourceSwitch == null) { // get declared DataSourceSwitch annotation dataSourceSwitch = userDeclaredMethod.getDeclaredAnnotation(DataSourceSwitch.class); } if (dataSourceSwitch != null) { // setting current thread use data source pool name DataSourceContextHolder.set(dataSourceSwitch.value()); } return invocation.proceed(); } finally { // remove current thread use datasource pool name DataSourceContextHolder.remove(); } }
Example 4
Source Project: spring-analysis-note File: AnnotationUtils.java License: MIT License | 6 votes |
/** * Find a single {@link Annotation} of {@code annotationType} on the supplied * {@link Method}, traversing its super methods (i.e. from superclasses and * interfaces) if the annotation is not <em>directly present</em> on the given * method itself. * <p>Correctly handles bridge {@link Method Methods} generated by the compiler. * <p>Meta-annotations will be searched if the annotation is not * <em>directly present</em> on the method. * <p>Annotations on methods are not inherited by default, so we need to handle * this explicitly. * @param method the method to look for annotations on * @param annotationType the annotation type to look for * @return the first matching annotation, or {@code null} if not found * @see #getAnnotation(Method, Class) */ @Nullable public static <A extends Annotation> A findAnnotation(Method method, @Nullable Class<A> annotationType) { if (annotationType == null) { return null; } // Shortcut: directly present on the element, with no merging needed? if (AnnotationFilter.PLAIN.matches(annotationType) || AnnotationsScanner.hasPlainJavaAnnotationsOnly(method)) { return method.getDeclaredAnnotation(annotationType); } // Exhaustive retrieval of merged annotations... return MergedAnnotations.from(method, SearchStrategy.EXHAUSTIVE, RepeatableContainers.none(), AnnotationFilter.PLAIN) .get(annotationType).withNonMergedAttributes() .synthesize(MergedAnnotation::isPresent).orElse(null); }
Example 5
Source Project: api-boot File: ResourceFieldLoader.java License: Apache License 2.0 | 6 votes |
/** * load method declared ResourceField Annotation List * * @param method declared method * @return ResourceField Annotation List */ public static List<ResourceField> getDeclaredResourceField(Method method) { List<ResourceField> resourceFieldList = new ArrayList(); // single ResourceField Annotation ResourceField resourceField = method.getDeclaredAnnotation(ResourceField.class); if (!ObjectUtils.isEmpty(resourceField)) { resourceFieldList.add(resourceField); } // multiple ResourceField Annotation ResourceFields ResourceFields = method.getDeclaredAnnotation(ResourceFields.class); if (!ObjectUtils.isEmpty(ResourceFields)) { resourceFieldList.addAll(Arrays.asList(ResourceFields.value())); } return resourceFieldList; }
Example 6
Source Project: Wizardry File: ModuleOverrideHandler.java License: GNU Lesser General Public License v3.0 | 6 votes |
/** * Returns a list of override methods from a given interface type. * * @param clazz the interface type to retrieve methods from. * @return a collection, mapping override names to their according methods. * @throws ModuleOverrideException if some issues with the reflection occurred. */ public static Map<String, Method> getInterfaceMethods(Class<?> clazz) throws ModuleOverrideException { HashMap<String, Method> overridableMethods = new HashMap<>(); for (Method method : clazz.getMethods()) { ModuleOverrideInterface ovrd = method.getDeclaredAnnotation(ModuleOverrideInterface.class); if (ovrd == null) continue; if (overridableMethods.containsKey(ovrd.value())) throw new ModuleOverrideException("Multiple methods exist in class '" + clazz + "' with same override name '" + ovrd.value() + "'."); try { method.setAccessible(true); } catch (SecurityException e) { throw new ModuleOverrideException("Failed to aquire reflection access to method '" + method.toString() + "', annotated by @ModuleOverrideInterface.", e); } overridableMethods.put(ovrd.value(), method); } return overridableMethods; }
Example 7
Source Project: api-boot File: ApiBootDataSourceSwitchAnnotationInterceptor.java License: Apache License 2.0 | 6 votes |
@Override public Object invoke(MethodInvocation invocation) throws Throwable { Object methodResult; try { Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null); Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass); Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); // get class declared DataSourceSwitch annotation DataSourceSwitch dataSourceSwitch = targetClass.getDeclaredAnnotation(DataSourceSwitch.class); if (dataSourceSwitch == null) { // get declared DataSourceSwitch annotation dataSourceSwitch = userDeclaredMethod.getDeclaredAnnotation(DataSourceSwitch.class); } if (dataSourceSwitch != null) { // setting current thread use data source pool name DataSourceContextHolder.set(dataSourceSwitch.value()); } methodResult = invocation.proceed(); } finally { // remove current thread use datasource pool name DataSourceContextHolder.remove(); } return methodResult; }
Example 8
Source Project: vert.x-microservice File: ServiceVerticle.java License: Apache License 2.0 | 6 votes |
private Object[] invokeBinaryEBParameters(Message<byte[]> m, Method method) { byte[] tmp = m.body(); final java.lang.reflect.Parameter[] parameters = method.getParameters(); final Object[] parameterResult = new Object[parameters.length]; final Consumes consumes = method.getDeclaredAnnotation(Consumes.class); int i = 0; for (java.lang.reflect.Parameter p : parameters) { if (p.getType().equals(EBMessageReply.class)) { final String consumesVal = consumes != null && consumes.value().length > 0 ? consumes.value()[0] : ""; parameterResult[i] = new EBMessageReply(this.vertx.eventBus(), m, consumesVal, getConverter()); } else { putTypedEBParameter(consumes, parameterResult, p, i, tmp); } i++; } return parameterResult; }
Example 9
Source Project: FS-Blog File: AspectUtil.java License: Apache License 2.0 | 6 votes |
/** * 获取连接点的制定类型的注解 * * @param joinPoint 连接点 * @param clazz 注解类 * * @return 注解 */ public static Annotation getAnnotation(ProceedingJoinPoint joinPoint, Class clazz) { try { // 拦截的对象 Object object = joinPoint.getTarget(); Signature signature = joinPoint.getSignature(); // 拦截方法名 String methodName = signature.getName(); Class[] parameterTypes = ((MethodSignature) signature).getMethod().getParameterTypes(); try { // 反射目标方法 Method method = object.getClass().getDeclaredMethod(methodName, parameterTypes); // 获取注解 return method.getDeclaredAnnotation(clazz); } catch (NoSuchMethodException e) { e.printStackTrace(); } } catch (Throwable throwable) { throwable.printStackTrace(); } return null; }
Example 10
Source Project: microprofile-fault-tolerance File: PureJ2SERetryVisibilityTest.java License: Apache License 2.0 | 5 votes |
@Test public void checkBaseRomRetryMissingOnMethod() throws Exception { Retry foundAnnotation; Method m = RetryOnMethodServiceNoAnnotationOnOverridedMethod.class.getDeclaredMethod("service"); foundAnnotation = m.getDeclaredAnnotation(Retry.class); Assert.assertNull(foundAnnotation, "no Retry annotation should be found on RetryOnMethodServiceNoAnnotationOnOverridedMethod#service() " + "via getDeclaredAnnotation()"); foundAnnotation = m.getAnnotation(Retry.class); Assert.assertNull(foundAnnotation, "no Retry annotation should be found on RetryOnMethodServiceNoAnnotationOnOverridedMethod#service() via getAnnotation()"); }
Example 11
Source Project: framework File: DynamicDataSourceChangeAdvice.java License: Apache License 2.0 | 5 votes |
/** * Description: <br> * * @author 王伟<br> * @taskId <br> * @param joinPoint * @return Object * @throws Throwable <br> */ @Around("change()") public Object around(final ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); DataSource dataSource = method.getDeclaredAnnotation(DataSource.class); if (dataSource != null) { DynamicDataSourceManager.setDataSourceCode(dataSource.value()); } else { Object target = joinPoint.getTarget(); dataSource = target.getClass().getDeclaredAnnotation(DataSource.class); if (dataSource != null) { DynamicDataSourceManager.setDataSourceCode(dataSource.value()); } } try { return joinPoint.proceed(); } finally { if (dataSource != null) { DynamicDataSourceManager.setDataSourceCode(DynamicDataSourceManager.DEFAULT_DATASOURCE_CODE); } } }
Example 12
Source Project: TencentKona-8 File: EventControl.java License: GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("unchecked") private void defineSettings(Class<?> eventClass) { // Iterate up the class hierarchy and let // subclasses shadow base classes. boolean allowPrivateMethod = true; while (eventClass != null) { for (Method m : eventClass.getDeclaredMethods()) { boolean isPrivate = Modifier.isPrivate(m.getModifiers()); if (m.getReturnType() == Boolean.TYPE && m.getParameterCount() == 1 && (!isPrivate || allowPrivateMethod)) { SettingDefinition se = m.getDeclaredAnnotation(SettingDefinition.class); if (se != null) { Class<?> settingClass = m.getParameters()[0].getType(); if (!Modifier.isAbstract(settingClass.getModifiers()) && SettingControl.class.isAssignableFrom(settingClass)) { String name = m.getName(); Name n = m.getAnnotation(Name.class); if (n != null) { name = n.value(); } if (!eventControls.containsKey(name)) { defineSetting((Class<? extends SettingControl>) settingClass, m, type, name); } } } } } eventClass = eventClass.getSuperclass(); allowPrivateMethod = false; } }
Example 13
Source Project: cloudbreak File: AbstractMinimalTest.java License: Apache License 2.0 | 5 votes |
private TestCaseDescription collectTestCaseDescription(TestContext testContext, Method method, Object[] params) { Description declaredAnnotation = method.getDeclaredAnnotation(Description.class); TestCaseDescription testCaseDescription = null; if (declaredAnnotation != null) { testCaseDescription = new TestCaseDescriptionBuilder() .given(declaredAnnotation.given()) .when(declaredAnnotation.when()) .then(declaredAnnotation.then()); testContext.addDescription(testCaseDescription); } else if (method.getParameters().length == params.length) { Parameter[] parameters = method.getParameters(); for (int i = 1; i < parameters.length; i++) { if (parameters[i].getAnnotation(Description.class) != null) { Object param = params[i]; if (!(param instanceof TestCaseDescription)) { throw new IllegalArgumentException("The param annotated with @Description but the type is should be " + TestCaseDescription.class.getSimpleName()); } testCaseDescription = (TestCaseDescription) param; testContext.addDescription(testCaseDescription); break; } } } return Optional.ofNullable(testCaseDescription) .filter(d -> !Strings.isNullOrEmpty(d.getValue())) .orElseThrow(() -> new TestCaseDescriptionMissingException(method.getName())); }
Example 14
Source Project: xian File: GroovyRuleController.java License: Apache License 2.0 | 5 votes |
@Override protected String getFirst() { if (!rules_first.containsKey(getClass())) { for (Method method : getClass().getDeclaredMethods()) { if (method.getDeclaredAnnotation(First.class) != null) { rules_first.put(getClass(), method.getName()); LOG.info("[RuleController" + getClass().getName() + "]的第一步 = " + method.getName()); break; } } } return rules_first.get(getClass()); }
Example 15
Source Project: Wizardry File: ModuleOverrideHandler.java License: GNU Lesser General Public License v3.0 | 4 votes |
/** * Returns a list of override methods from a given type, implementing them. * * @param clazz the type. * @param hasContext if <code>true</code> then the method may contain context parameters. * @return a collection, mapping override names to their according methods. * @throws ModuleInitException if a method exists having invalid argument types or if some issues with reflection occurred. */ static HashMap<String, OverrideMethod> getOverrideMethodsFromClass(Class<?> clazz, boolean hasContext) throws ModuleInitException { HashMap<String, OverrideMethod> overridableMethods = new HashMap<>(); // Determine overriden methods via reflection // FIXME: Separation of concerns: Overridable methods are not part of factory. Move them or rename factory class appropriately. for (Method method : clazz.getMethods()) { ModuleOverride ovrd = method.getDeclaredAnnotation(ModuleOverride.class); if (ovrd == null) continue; if (overridableMethods.containsKey(ovrd.value())) throw new ModuleInitException("Multiple methods exist in class '" + clazz + "' with same override name '" + ovrd.value() + "'."); try { method.setAccessible(true); } catch (SecurityException e) { throw new ModuleInitException("Failed to aquire reflection access to method '" + method.toString() + "', annotated by @ModuleOverride.", e); } // Search for context parameters int idxContextParamRing = -1; int idxContextParamSuper = -2; Parameter[] params = method.getParameters(); for (int i = 0; i < params.length; i++) { Parameter param = params[i]; if (param.isAnnotationPresent(ContextRing.class)) { if (idxContextParamRing >= 0) throw new ModuleInitException("Method '" + method.toString() + "' has invalid @ContextRing annotated parameter. It is not allowed on multiple parameters."); idxContextParamRing = i; } if (param.isAnnotationPresent(ContextSuper.class)) { if (idxContextParamSuper >= 0) throw new ModuleInitException("Method '" + method.toString() + "' has invalid @ContextSuper annotated parameter. It is not allowed on multiple parameters."); idxContextParamSuper = i; } } if (!hasContext) { if (idxContextParamRing >= 0 || idxContextParamSuper >= 0) throw new ModuleInitException("Context parameters are not allowed."); } if (idxContextParamRing == idxContextParamSuper) throw new ModuleInitException("Method '" + method.toString() + "' has a parameter which is annotated with multiple roles."); OverrideMethod ovrdMethod = new OverrideMethod(method, idxContextParamRing, idxContextParamSuper); overridableMethods.put(ovrd.value(), ovrdMethod); } return overridableMethods; }
Example 16
Source Project: ignite File: GridServiceProxy.java License: Apache License 2.0 | 4 votes |
/** * @param mtd Method to invoke. */ String methodName(Method mtd) { PlatformServiceMethod ann = mtd.getDeclaredAnnotation(PlatformServiceMethod.class); return ann == null ? mtd.getName() : ann.value(); }
Example 17
Source Project: enkan File: NonJtaTransactionMiddleware.java License: Eclipse Public License 1.0 | 4 votes |
private Transactional.TxType getTransactionType(Method m) { Transactional transactional = m.getDeclaredAnnotation(Transactional.class); return transactional != null ? transactional.value() : null; }
Example 18
Source Project: vert.x-microservice File: ServiceVerticle.java License: Apache License 2.0 | 4 votes |
private Operation mapServiceMethod(Method method) { final Path path = method.getDeclaredAnnotation(Path.class); final Produces produces = method.getDeclaredAnnotation(Produces.class); final Consumes consumes = method.getDeclaredAnnotation(Consumes.class); final OperationType opType = method.getDeclaredAnnotation(OperationType.class); if (opType == null) throw new MissingResourceException("missing OperationType ", this.getClass().getName(), ""); final String[] mimeTypes = produces != null ? produces.value() : null; final String[] consumeTypes = consumes != null ? consumes.value() : null; final String url = serviceName().concat(path.value()); final List<String> parameters = new ArrayList<>(); switch (opType.value()) { case REST_POST: parameters.addAll(getAllRESTParameters(method)); vertx.eventBus().consumer(url, handler -> genericRESTHandler(handler, method)); break; case REST_GET: parameters.addAll(getAllRESTParameters(method)); // TODO extract to method router.get(url).handler(routingContext -> { getParameterEntity(routingContext.request().params()).getAll().forEach(elem -> { System.out.println("--> " + elem.getName() + " : " + elem.getValue()); }); genericLocalRESTHandler(routingContext,method); }); vertx.eventBus().consumer(url, handler -> genericRESTHandler(handler, method)); break; case WEBSOCKET: parameters.addAll(getWSParameter(method)); vertx.eventBus().consumer(url, (Handler<Message<byte[]>>) handler -> genericWSHandler(handler, method)); break; case EVENTBUS: List<String> parameter = getEVENTBUSParameter(method); parameters.addAll(parameter); registerEventBusMethod(method, consumes, url, parameter); break; } // TODO add service description!!! return new Operation(path.value(), null, url, opType.value().name(), mimeTypes, consumeTypes, parameters.toArray(new String[parameters.size()])); }
Example 19
Source Project: enkan File: TransactionMiddleware.java License: Eclipse Public License 1.0 | 4 votes |
private Transactional.TxType getTransactionType(Method m) { Transactional transactional = m.getDeclaredAnnotation(Transactional.class); return transactional != null ? transactional.value() : null; }
Example 20
Source Project: huntbugs File: TestNoRuntimeRetention.java License: Apache License 2.0 | 4 votes |
@AssertNoWarning("*") public boolean testRuntimeRetention(Method m) { return m.getDeclaredAnnotation(MyAnnoRuntime.class) != null; }