List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:com.aftabsikander.permissionassist.PermissionAssistant.java
private static void runAnnotatedMethods(@NonNull Object object, int requestCode) { Class clazz = object.getClass(); if (isUsingAndroidAnnotations(object)) { clazz = clazz.getSuperclass();//w w w . j a v a2 s . c om } while (clazz != null) { for (Method method : clazz.getDeclaredMethods()) { if (method.isAnnotationPresent(AfterPermissionGranted.class)) { // Check for annotated methods with matching request code. AfterPermissionGranted ann = method.getAnnotation(AfterPermissionGranted.class); if (ann.value() == requestCode) { // Method must be void so that we can invoke it if (method.getParameterTypes().length > 0) { throw new RuntimeException("Cannot execute method " + method.getName() + " because it is non-void method and/or has input parameters."); } try { // Make method accessible if private if (!method.isAccessible()) { method.setAccessible(true); } method.invoke(object); } catch (IllegalAccessException e) { Log.e(TAG, "runDefaultMethod:IllegalAccessException", e); } catch (InvocationTargetException e) { Log.e(TAG, "runDefaultMethod:InvocationTargetException", e); } } } } clazz = clazz.getSuperclass(); } }
From source file:org.jboss.errai.codegen.util.CDIAnnotationUtils.java
/** * <p>Generate a hash code for the given annotation using the algorithm * presented in the {@link Annotation#hashCode()} API docs.</p> * * @param a the Annotation for a hash code calculation is desired, not * {@code null}//from www .ja v a 2 s . c o m * @return the calculated hash code * @throws RuntimeException if an {@code Exception} is encountered during * annotation member access * @throws IllegalStateException if an annotation method invocation returns * {@code null} */ public static int hashCode(Annotation a) { int result = 0; final Class<? extends Annotation> type = a.annotationType(); for (final Method m : type.getDeclaredMethods()) { if (!m.isAnnotationPresent(Nonbinding.class)) { try { final Object value = m.invoke(a); if (value == null) { throw new IllegalStateException(String.format("Annotation method %s returned null", m)); } result += hashMember(m.getName(), value); } catch (final RuntimeException ex) { throw ex; } catch (final Exception ex) { throw new RuntimeException(ex); } } } return result; }
From source file:org.jboss.errai.ioc.util.CDIAnnotationUtils.java
/** * <p>Checks if two annotations are equal using the criteria for equality * presented in the {@link Annotation#equals(Object)} API docs.</p> * * @param a1 the first Annotation to compare, {@code null} returns * {@code false} unless both are {@code null} * @param a2 the second Annotation to compare, {@code null} returns * {@code false} unless both are {@code null} * @return {@code true} if the two annotations are {@code equal} or both * {@code null}//from w ww .j a v a2 s . c o m */ public static boolean equals(Annotation a1, Annotation a2) { if (a1 == a2) { return true; } if (a1 == null || a2 == null) { return false; } Class<? extends Annotation> type = a1.annotationType(); Class<? extends Annotation> type2 = a2.annotationType(); Validate.notNull(type, "Annotation %s with null annotationType()", a1); Validate.notNull(type2, "Annotation %s with null annotationType()", a2); if (!type.equals(type2)) { return false; } try { for (Method m : type.getDeclaredMethods()) { if (m.getParameterTypes().length == 0 && isValidAnnotationMemberType(m.getReturnType()) && !m.isAnnotationPresent(Nonbinding.class)) { Object v1 = m.invoke(a1); Object v2 = m.invoke(a2); if (!memberEquals(m.getReturnType(), v1, v2)) { return false; } } } } catch (IllegalAccessException ex) { return false; } catch (InvocationTargetException ex) { return false; } return true; }
From source file:com.jhkt.playgroundArena.db.nosql.mongodb.beans.AbstractDocument.java
private final static Object convertBacktoClassInstanceHelper(DBObject dBObject) { Object returnValue = null;// w ww . ja v a 2s . c o m try { String className = dBObject.get(JPAConstants.CONVERTER_CLASS.CLASS.name()).toString(); Class<?> classCheck = Class.forName(className); if (AbstractDocument.class.isAssignableFrom(classCheck)) { Class<? extends AbstractDocument> classToConvertTo = classCheck.asSubclass(AbstractDocument.class); AbstractDocument dInstance = classToConvertTo.newInstance(); for (String key : dBObject.keySet()) { Object value = dBObject.get(key); char[] propertyChars = key.toCharArray(); String methodMain = String.valueOf(propertyChars[0]).toUpperCase() + key.substring(1); String methodName = "set" + methodMain; String getMethodName = "get" + methodMain; if (key.equals(JPAConstants.CONVERTER_CLASS.CLASS.name())) { continue; } if (value instanceof BasicDBObject) { value = convertBacktoClassInstanceHelper(BasicDBObject.class.cast(value)); } try { Method getMethod = classToConvertTo.getMethod(getMethodName); Class<?> getReturnType = getMethod.getReturnType(); Method method = classToConvertTo.getMethod(methodName, getReturnType); if (getMethod.isAnnotationPresent(IDocumentKeyValue.class)) { method.invoke(dInstance, value); } } catch (NoSuchMethodException nsMe) { _log.warn("Within convertBacktoClassInstance, following method was not found " + methodName, nsMe); } } returnValue = dInstance; } else if (Enum.class.isAssignableFrom(classCheck)) { List<?> constants = Arrays.asList(classCheck.getEnumConstants()); String name = String.class.cast(dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name())); for (Object constant : constants) { if (constant.toString().equals(name)) { returnValue = constant; } } } else if (Collection.class.isAssignableFrom(classCheck)) { @SuppressWarnings("unchecked") Class<? extends Collection<? super Object>> classToConvertTo = (Class<? extends Collection<? super Object>>) classCheck; Collection<? super Object> cInstance = classToConvertTo.newInstance(); BasicDBList bDBList = (BasicDBList) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name()); cInstance.addAll(bDBList); returnValue = cInstance; } else if (Map.class.isAssignableFrom(classCheck)) { @SuppressWarnings("unchecked") Class<? extends Map<String, ? super Object>> classToConvertTo = (Class<? extends Map<String, ? super Object>>) classCheck; Map<String, ? super Object> mInstance = classToConvertTo.newInstance(); BasicDBObject mapObject = (BasicDBObject) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name()); mInstance.putAll(mapObject); returnValue = mInstance; } } catch (Exception e) { throw new RuntimeException(e); } return returnValue; }
From source file:android.reflect.ClazzLoader.java
/** * ?//w ww. ja v a 2s . c om */ public static Method getSingleMethodByAnnotation(Class<?> clazz, Class<? extends Annotation> annClazz) { Method method = null; if (clazz != null && annClazz != null) { Method[] methods = clazz.getMethods(); if (Assert.notEmpty(methods)) { for (Method m : methods) { if (m != null && m.isAnnotationPresent(annClazz)) { method = m; break; } } } } return method; }
From source file:xiaofei.library.hermes.util.TypeUtils.java
public static Method getMethodForGettingInstance(Class<?> clazz, String methodName, Class<?>[] parameterTypes) throws HermesException { Method[] methods = clazz.getMethods(); Method result = null;//from w ww.j a v a 2s. com for (Method method : methods) { String tmpName = method.getName(); if (methodName.equals("") && (tmpName.equals("getInstance") || method.isAnnotationPresent(GetInstance.class)) || !methodName.equals("") && tmpName.equals(methodName)) { if (classAssignable(method.getParameterTypes(), parameterTypes)) { if (result == null) { result = method; } else { throw new HermesException(ErrorCodes.TOO_MANY_MATCHING_METHODS_FOR_GETTING_INSTANCE, "When getting instance, there are more than one method named " + methodName + " of the class " + clazz.getName() + " matching the parameters!"); } } } } if (result != null) { if (result.getReturnType() != clazz) { throw new HermesException(ErrorCodes.GETTING_INSTANCE_RETURN_TYPE_ERROR, "When getting instance, the method named " + methodName + " of the class " + clazz.getName() + " matches the parameter types but not the return type. The return type is " + result.getReturnType().getName() + " but the required type is " + clazz.getName() + "."); } return result; } throw new HermesException(ErrorCodes.GETTING_INSTANCE_METHOD_NOT_FOUND, "When getting instance, the method named " + methodName + " of the class " + clazz.getName() + " is not found. The class must have a method for getting instance."); }
From source file:com.zc.util.refelect.Reflector.java
/** * ?methodannotationClass/*from w w w . j a va 2 s .c o m*/ * * @param method * method * @param annotationClass * annotationClass * * @return {@link java.lang.annotation.Annotation} */ public static <T extends Annotation> T getAnnotation(Method method, Class annotationClass) { method.setAccessible(true); if (method.isAnnotationPresent(annotationClass)) { return (T) method.getAnnotation(annotationClass); } return null; }
From source file:org.jspare.forvertx.web.collector.HandlerCollector.java
public static Collection<HandlerData> collect(Transporter transporter, Class<?> clazz) { List<HandlerData> collectedHandlers = new ArrayList<>(); List<Annotation> httpMethodsAnnotations = new ArrayList<>(getHttpMethodsPresents(clazz)); boolean hasAuthClass = clazz.isAnnotationPresent(Auth.class); Auth authClass = clazz.getAnnotation(Auth.class); for (Method method : clazz.getDeclaredMethods()) { if (!isHandler(method)) { continue; }/* ww w. jav a 2 s . c om*/ final List<Annotation> handlerHttpMethodsAnnotations = new ArrayList<>(); handlerHttpMethodsAnnotations.addAll(httpMethodsAnnotations); String consumes = method.isAnnotationPresent(Consumes.class) ? method.getAnnotation(Consumes.class).value() : StringUtils.EMPTY; String produces = method.isAnnotationPresent(Produces.class) ? method.getAnnotation(Produces.class).value() : StringUtils.EMPTY; Class<? extends Handler<RoutingContext>> routeHandlerClass = transporter.getRouteHandlerClass(); List<org.jspare.forvertx.web.handler.BodyEndHandler> bodyEndHandler = collectBodyEndHandlers( transporter, method); boolean hasMethodAuth = false; boolean skipAuthorities = false; String autority = StringUtils.EMPTY; HandlerDocumentation hDocumentation = null; if (method.isAnnotationPresent(Documentation.class)) { Documentation documentation = method.getAnnotation(Documentation.class); hDocumentation = new HandlerDocumentation(); hDocumentation.description(documentation.description()); hDocumentation.status(Arrays.asList(documentation.responseStatus()).stream() .map(s -> new HandlerDocumentation.ResponseStatus(s)).collect(Collectors.toList())); hDocumentation.queryParameters(Arrays.asList(documentation.queryParameters()).stream() .map(q -> new HandlerDocumentation.QueryParameter(q)).collect(Collectors.toList())); hDocumentation.requestSchema(documentation.requestClass()); hDocumentation.responseSchema(documentation.responseClass()); } if (!method.isAnnotationPresent(IgnoreAuth.class)) { if (method.isAnnotationPresent(Auth.class)) { Auth auth = method.getAnnotation(Auth.class); hasMethodAuth = true; skipAuthorities = auth.skipAuthorities(); autority = StringUtils.defaultIfEmpty(auth.value(), StringUtils.EMPTY); } else { if (hasAuthClass) { hasMethodAuth = true; skipAuthorities = authClass.skipAuthorities(); autority = StringUtils.defaultIfEmpty(authClass.value(), StringUtils.EMPTY); } } } HandlerData defaultHandlerData = new HandlerData().clazz(clazz).method(method).consumes(consumes) .produces(produces).bodyEndHandler(bodyEndHandler).auth(hasMethodAuth) .skipAuthorities(skipAuthorities).autority(autority).authProvider(transporter.getAuthProvider()) .routeHandler(routeHandlerClass).documentation(hDocumentation); if (hasHttpMethodsPresents(method)) { handlerHttpMethodsAnnotations.clear(); handlerHttpMethodsAnnotations.addAll(getHttpMethodsPresents(method)); } getHandlersPresents(method).forEach(handlerType -> { try { // Extract order from Handler, all Hanlder having order() // method int order = annotationMethod(handlerType, "order"); HandlerData handlerData = (HandlerData) defaultHandlerData.clone(); handlerData.order(order); if (isHandlerAnnotation(handlerType, org.jspare.forvertx.web.mapping.handlers.Handler.class)) { handlerData.handlerType(HandlerType.HANDLER); } else if (isHandlerAnnotation(handlerType, FailureHandler.class)) { handlerData.handlerType(HandlerType.HANDLER); } else if (isHandlerAnnotation(handlerType, BlockingHandler.class)) { handlerData.handlerType(HandlerType.BLOCKING_HANDLER); } if (handlerHttpMethodsAnnotations.isEmpty()) { collectedHandlers.add(handlerData); } else { collectedHandlers.addAll(collectByMethods(handlerData, handlerHttpMethodsAnnotations)); } } catch (Exception e) { log.warn("Ignoring handler class {} method {} - {}", clazz.getName(), method.getName(), e.getMessage()); } }); } return collectedHandlers; }
From source file:com.ace.erp.common.inject.support.InjectBaseDependencyHelper.java
/** * ??/*from w w w .ja v a 2 s .co m*/ * * @param target * @param annotation */ private static Set<Object> findDependencies(final Object target, final Class<? extends Annotation> annotation) { final Set<Object> candidates = Sets.newHashSet(); ReflectionUtils.doWithFields(target.getClass(), new ReflectionUtils.FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(field); Object obj = ReflectionUtils.getField(field, target); candidates.add(obj); } }, new ReflectionUtils.FieldFilter() { @Override public boolean matches(Field field) { return field.isAnnotationPresent(annotation); } }); ReflectionUtils.doWithMethods(target.getClass(), new ReflectionUtils.MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { ReflectionUtils.makeAccessible(method); PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method); candidates.add(ReflectionUtils.invokeMethod(descriptor.getReadMethod(), target)); } }, new ReflectionUtils.MethodFilter() { @Override public boolean matches(Method method) { boolean hasAnnotation = false; hasAnnotation = method.isAnnotationPresent(annotation); if (!hasAnnotation) { return false; } boolean hasReadMethod = false; PropertyDescriptor descriptor = BeanUtils.findPropertyForMethod(method); hasReadMethod = descriptor != null && descriptor.getReadMethod() != null; if (!hasReadMethod) { return false; } return true; } }); return candidates; }
From source file:org.jboss.errai.codegen.util.CDIAnnotationUtils.java
/** * <p>Checks if two annotations are equal using the criteria for equality * presented in the {@link Annotation#equals(Object)} API docs.</p> * * @param a1 the first Annotation to compare, {@code null} returns * {@code false} unless both are {@code null} * @param a2 the second Annotation to compare, {@code null} returns * {@code false} unless both are {@code null} * @return {@code true} if the two annotations are {@code equal} or both * {@code null}/*w w w . ja v a2s. c om*/ */ public static boolean equals(Annotation a1, Annotation a2) { if (a1 == a2) { return true; } if (a1 == null || a2 == null) { return false; } final Class<? extends Annotation> type = a1.annotationType(); final Class<? extends Annotation> type2 = a2.annotationType(); Validate.notNull(type, "Annotation %s with null annotationType()", a1); Validate.notNull(type2, "Annotation %s with null annotationType()", a2); if (!type.equals(type2)) { return false; } try { for (final Method m : type.getDeclaredMethods()) { if (m.getParameterTypes().length == 0 && isValidAnnotationMemberType(m.getReturnType()) && !m.isAnnotationPresent(Nonbinding.class)) { final Object v1 = m.invoke(a1); final Object v2 = m.invoke(a2); if (!memberEquals(m.getReturnType(), v1, v2)) { return false; } } } } catch (final IllegalAccessException ex) { return false; } catch (final InvocationTargetException ex) { return false; } return true; }