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

The following examples show how to use java.lang.reflect.Method#getAnnotations() . 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: StandardAnnotationMetadata.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public Set<MethodMetadata> getAnnotatedMethods(String annotationName) {
	try {
		Method[] methods = getIntrospectedClass().getDeclaredMethods();
		Set<MethodMetadata> annotatedMethods = new LinkedHashSet<MethodMetadata>();
		for (Method method : methods) {
			if (!method.isBridge() && method.getAnnotations().length > 0 &&
					AnnotatedElementUtils.isAnnotated(method, annotationName)) {
				annotatedMethods.add(new StandardMethodMetadata(method, this.nestedAnnotationsAsMap));
			}
		}
		return annotatedMethods;
	}
	catch (Throwable ex) {
		throw new IllegalStateException("Failed to introspect annotated methods on " + getIntrospectedClass(), ex);
	}
}
 
Example 2
Source File: JavassistUtils.java    From statefulj with Apache License 2.0 6 votes vote down vote up
public static void addMethodAnnotations(CtMethod ctMethod, Method method) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
	if (method != null) {
		MethodInfo methodInfo = ctMethod.getMethodInfo();
		ConstPool constPool = methodInfo.getConstPool();
		AnnotationsAttribute attr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
		methodInfo.addAttribute(attr);
		for(java.lang.annotation.Annotation anno : method.getAnnotations()) {

			// If it's a Transition skip
			// TODO : Make this a parameterized set of Filters instead of hardcoding
			//
			Annotation clone = null;
			if (anno instanceof Transitions || anno instanceof Transition) {
				// skip
			} else {
				clone = cloneAnnotation(constPool, anno);
				attr.addAnnotation(clone);
			}
		}
	}
}
 
Example 3
Source File: ControlInitializerSupport.java    From jdal with Apache License 2.0 6 votes vote down vote up
/**
 * Get field or method annotations
 * @param property
 * @param clazz
 * @return
 */
protected Annotation[] getAnnotations(String property, Class<?> clazz) {
	Field field = ReflectionUtils.findField(clazz, property);
	Annotation[] fa = new Annotation[] {};
	
	if (field != null) {
		fa = field.getAnnotations();
	}
	
	Method method = PropertyUtils.getPropertyDescriptor(clazz, property).getReadMethod();
	if (method != null) {
		Annotation[] ma = method.getAnnotations();
		Annotation[] annotations = (Annotation[]) ArrayUtils.addAll(fa, ma);
		return annotations;
	}
	
	return fa;
}
 
Example 4
Source File: AnnotationUtils.java    From valdr-bean-validation with MIT License 6 votes vote down vote up
private static boolean isInterfaceWithAnnotatedMethods(Class<?> iface) {
  synchronized (annotatedInterfaceCache) {
    Boolean flag = annotatedInterfaceCache.get(iface);
    if (flag != null) {
      return flag;
    }
    boolean found = false;
    for (Method ifcMethod : iface.getMethods()) {
      if (ifcMethod.getAnnotations().length > 0) {
        found = true;
        break;
      }
    }
    annotatedInterfaceCache.put(iface, found);
    return found;
  }
}
 
Example 5
Source File: StandardAnnotationMetadata.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean hasAnnotatedMethods(String annotationName) {
	try {
		Method[] methods = getIntrospectedClass().getDeclaredMethods();
		for (Method method : methods) {
			if (!method.isBridge() && method.getAnnotations().length > 0 &&
					AnnotatedElementUtils.isAnnotated(method, annotationName)) {
				return true;
			}
		}
		return false;
	}
	catch (Throwable ex) {
		throw new IllegalStateException("Failed to introspect annotated methods on " + getIntrospectedClass(), ex);
	}
}
 
Example 6
Source File: AbstractSearchQueryDto.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
private List<Method> findMatchingAnnotatedMethods(String parameterName) {
  List<Method> result = new ArrayList<Method>();
  Method[] methods = this.getClass().getMethods();
  for (int i = 0; i < methods.length; i++) {
    Method method = methods[i];
    Annotation[] methodAnnotations = method.getAnnotations();

    for (int j = 0; j < methodAnnotations.length; j++) {
      Annotation annotation = methodAnnotations[j];
      if (annotation instanceof CamundaQueryParam) {
        CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation;
        if (parameterAnnotation.value().equals(parameterName)) {
          result.add(method);
        }
      }
    }
  }
  return result;
}
 
Example 7
Source File: RuntimeInlineAnnotationReader.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public Annotation[] getAllMethodAnnotations(Method method, Locatable srcPos) {
    Annotation[] r = method.getAnnotations();
    for( int i=0; i<r.length; i++ ) {
        r[i] = LocatableAnnotation.create(r[i],srcPos);
    }
    return r;
}
 
Example 8
Source File: InjectionPoint.java    From baratine with GNU General Public License v2.0 5 votes vote down vote up
static <T> InjectionPoint<T> of(Method m)
{
  return new InjectionPointImpl<>(Key.of(m),
      m.getGenericReturnType(),
      m.getName(),
      m.getAnnotations(),
      m.getDeclaringClass());
}
 
Example 9
Source File: AnnotationInterceptor.java    From oxygen with Apache License 2.0 5 votes vote down vote up
@Override
public boolean match(Method method) {
  for (Annotation annotation : method.getAnnotations()) {
    if (annotation.annotationType() == this.targetAnnotation) {
      return true;
    }
  }
  return false;
}
 
Example 10
Source File: AnnotationUtils.java    From conf4j with MIT License 5 votes vote down vote up
public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
    Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method);
    A ann = resolvedMethod.getAnnotation(annotationType);
    if (ann == null) {
        for (Annotation metaAnn : resolvedMethod.getAnnotations()) {
            ann = metaAnn.annotationType().getAnnotation(annotationType);
            if (ann != null) {
                break;
            }
        }
    }
    return ann;
}
 
Example 11
Source File: MirrorValidator.java    From mirror with Apache License 2.0 5 votes vote down vote up
private void validateMethodAnnotations(Method method) {
    int[] counts = new int[5];
    for (Annotation annotation : method.getAnnotations()) {
        java.lang.Class<? extends Annotation> aClass = annotation.annotationType();
        if (aClass.equals(Constructor.class)) {
            counts[0]++;
        } else if (aClass.equals(GetField.class)) {
            counts[1]++;
        } else if (aClass.equals(SetField.class)) {
            counts[2]++;
        } else if (aClass.equals(GetInstance.class)) {
            counts[3]++;
        } else if (aClass.equals(SetInstance.class)) {
            counts[4]++;
        }
    }
    if (counts[1] > 1) {
        throw new MirrorException("too much GetField");
    }
    if (counts[2] > 1) {
        throw new MirrorException("too much SetField");
    }

    boolean found = false;
    for (int i = 0; i < counts.length; i++) {
        if (counts[i] > 0) {
            if (found) {
                throw new MirrorException("mixing invalid annotations");
            } else {
                found = true;
            }
        }
    }
}
 
Example 12
Source File: AnnotationsExtractor.java    From quickperf with Apache License 2.0 5 votes vote down vote up
public Annotation[] extractAnnotationsFor(Method testMethod, SetOfAnnotationConfigs testAnnotationConfigs) {
    Annotation[] classAnnotations = testMethod.getDeclaringClass().getAnnotations();
    Annotation[] methodAnnotations = testMethod.getAnnotations();
    Annotation[] mergedAnnotations = annotationsMerger.merge(globalAnnotations
                                                            , classAnnotations
                                                            , methodAnnotations);

    Collection<Annotation> quickPerfAnnotations = testAnnotationConfigs.keepQuickPerfAnnotationsIn(mergedAnnotations);

    List<Annotation> resultAsList
            = testAnnotationConfigs.removeDisabledAndAndDisablingAnnotationsIn(quickPerfAnnotations);

    return resultAsList.toArray(new Annotation[0]);
}
 
Example 13
Source File: MessageListenerBeanPostProcessor.java    From koper with Apache License 2.0 5 votes vote down vote up
/**
 * 获取第一个方法
 *
 * @param clazz
 * @param methodName
 * @return
 */
protected Method getMethod(Class<?> clazz, String methodName) {

    Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz); //clazz.getDeclaredMethods();
    Method findMethod = null;
    for (Method method : methods) {
        if (method.getName().equals(methodName)
                && method.getAnnotations().length != 0) {
            findMethod = method;
        }
    }
    return findMethod;
}
 
Example 14
Source File: AbstractSearchQueryDto.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
private Class<? extends JacksonAwareStringToTypeConverter<?>> findAnnotatedTypeConverter(Method method) {
  Annotation[] methodAnnotations = method.getAnnotations();

  for (int j = 0; j < methodAnnotations.length; j++) {
    Annotation annotation = methodAnnotations[j];
    if (annotation instanceof CamundaQueryParam) {
      CamundaQueryParam parameterAnnotation = (CamundaQueryParam) annotation;
      return parameterAnnotation.converter();
    }
  }
  return null;
}
 
Example 15
Source File: AnnotationReader.java    From xlsbeans with Apache License 2.0 5 votes vote down vote up
public Annotation[] getAnnotations(Class<?> clazz, Method method) throws Exception {
  if (xmlInfo != null && xmlInfo.getClassInfo(clazz.getName()) != null) {
    ClassInfo classInfo = xmlInfo.getClassInfo(clazz.getName());
    if (classInfo.getMethodInfo(method.getName()) != null) {
      MethodInfo methodInfo = classInfo.getMethodInfo(method.getName());
      List<Annotation> list = new ArrayList<Annotation>();
      for (AnnotationInfo annInfo : methodInfo.getAnnotationInfos()) {
        list.add(DynamicAnnotationBuilder.buildAnnotation(
            Class.forName(annInfo.getAnnotationClass()), annInfo));
      }
      return list.toArray(new Annotation[list.size()]);
    }
  }
  return method.getAnnotations();
}
 
Example 16
Source File: BeanUtilTest.java    From mango with Apache License 2.0 5 votes vote down vote up
private Set<Annotation> methodAnnos(Method m) {
  Set<Annotation> annos = new HashSet<Annotation>();
  for (Annotation anno : m.getAnnotations()) {
    annos.add(anno);
  }
  return annos;
}
 
Example 17
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Annotation[] getExtraAnnotations() {
    try {
        Method m = BookBean.class.getMethod("setUriInfo", new Class[]{UriInfo.class});
        return m.getAnnotations();
    } catch (Throwable ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 18
Source File: ReflectUtils.java    From saluki with Apache License 2.0 5 votes vote down vote up
public static Annotation findAnnotationFromMethod(Method method,
    Class<? extends Annotation> annotation) {
  for (Annotation targetAnnotation : method.getAnnotations()) {
    if (annotation.isAssignableFrom(targetAnnotation.annotationType())) {
      return targetAnnotation;
    } else {
      continue;
    }
  }
  return null;
}
 
Example 19
Source File: HwvtepSouthboundIT.java    From ovsdb with Eclipse Public License 1.0 4 votes vote down vote up
@Before
@Override
public void setup() throws Exception {
    if (setup) {
        LOG.info("Skipping setup, already initialized");
        return;
    }

    super.setup();

    addressStr = bundleContext.getProperty(SERVER_IPADDRESS);
    String portStr = bundleContext.getProperty(SERVER_PORT);
    try {
        portNumber = Integer.parseInt(portStr);
    } catch (NumberFormatException e) {
        fail("Invalid port number " + portStr + System.lineSeparator() + usage() + e);
    }

    connectionType = bundleContext.getProperty(CONNECTION_TYPE);

    LOG.info("setUp: Using the following properties: mode= {}, ip:port= {}:{}",
            connectionType, addressStr, portNumber);
    if (connectionType.equalsIgnoreCase(CONNECTION_TYPE_ACTIVE)) {
        if (addressStr == null) {
            fail(usage());
        }
    }

    mdsalUtils = new MdsalUtils(dataBroker);
    assertTrue("Did not find " + HwvtepSouthboundConstants.HWVTEP_TOPOLOGY_ID.getValue(), getHwvtepTopology());
    final ConnectionInfo connectionInfo = getConnectionInfo(addressStr, portNumber);
    final InstanceIdentifier<Node> iid = HwvtepSouthboundUtils.createInstanceIdentifier(connectionInfo);
    final DataTreeIdentifier<Node> treeId = DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, iid);

    dataBroker.registerDataTreeChangeListener(treeId, OPERATIONAL_LISTENER);

    hwvtepNode = connectHwvtepNode(connectionInfo);
    // Let's count the test methods (we need to use this instead of @AfterClass on teardown() since the latter is
    // useless with pax-exam)
    for (Method method : getClass().getMethods()) {
        boolean testMethod = false;
        boolean ignoreMethod = false;
        for (Annotation annotation : method.getAnnotations()) {
            if (Test.class.equals(annotation.annotationType())) {
                testMethod = true;
            }
            if (Ignore.class.equals(annotation.annotationType())) {
                ignoreMethod = true;
            }
        }
        if (testMethod && !ignoreMethod) {
            testMethodsRemaining++;
        }
    }
    LOG.info("{} test methods to run", testMethodsRemaining);

    setup = true;
}
 
Example 20
Source File: ReflectAnnotationReader.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public Annotation[] getAnnotations(Method m) {
        return m.getAnnotations();
}