List of usage examples for java.lang.reflect Method getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:com.datatorrent.stram.appdata.AppDataPushAgent.java
private JSONObject extractFields(Object o) { List<Field> fields; Map<String, Method> methods; if (cacheFields.containsKey(o.getClass())) { fields = cacheFields.get(o.getClass()); } else {//from w w w .ja v a 2 s . c om fields = new ArrayList<Field>(); for (Class<?> c = o.getClass(); c != Object.class; c = c.getSuperclass()) { Field[] declaredFields = c.getDeclaredFields(); for (Field field : declaredFields) { field.setAccessible(true); AutoMetric rfa = field.getAnnotation(AutoMetric.class); if (rfa != null) { field.setAccessible(true); try { fields.add(field); } catch (Exception ex) { LOG.debug("Error extracting fields for app data: {}. Ignoring.", ex.getMessage()); } } } } cacheFields.put(o.getClass(), fields); } JSONObject result = new JSONObject(); for (Field field : fields) { try { result.put(field.getName(), field.get(o)); } catch (Exception ex) { // ignore } } if (cacheGetMethods.containsKey(o.getClass())) { methods = cacheGetMethods.get(o.getClass()); } else { methods = new HashMap<String, Method>(); try { BeanInfo info = Introspector.getBeanInfo(o.getClass()); for (PropertyDescriptor pd : info.getPropertyDescriptors()) { Method method = pd.getReadMethod(); if (pd.getReadMethod() != null) { AutoMetric rfa = method.getAnnotation(AutoMetric.class); if (rfa != null) { methods.put(pd.getName(), method); } } } } catch (IntrospectionException ex) { // ignore } cacheGetMethods.put(o.getClass(), methods); } for (Map.Entry<String, Method> entry : methods.entrySet()) { try { result.put(entry.getKey(), entry.getValue().invoke(o)); } catch (Exception ex) { // ignore } } return result; }
From source file:mondrian.util.UtilCompatibleJdk15.java
@SuppressWarnings("unchecked") public <T> T getAnnotation(Method method, String annotationClassName, T defaultValue) { try {//from ww w . j a va 2s .com Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) Class .forName(annotationClassName); if (method.isAnnotationPresent(annotationClass)) { final Annotation annotation = method.getAnnotation(annotationClass); final Method method1 = annotation.getClass().getMethod("value"); return (T) method1.invoke(annotation); } } catch (IllegalAccessException e) { return defaultValue; } catch (InvocationTargetException e) { return defaultValue; } catch (NoSuchMethodException e) { return defaultValue; } catch (ClassNotFoundException e) { return defaultValue; } return defaultValue; }
From source file:org.brushingbits.jnap.struts2.interceptor.RestWorkflowInterceptor.java
/** * @param invocation// w w w .j av a 2 s .c om * @param action */ protected String findResultName(ActionInvocation invocation, Object action) { String resultName = Action.INPUT; try { Map<String, Object> session = ActionContext.getContext().getSession(); Method method = action.getClass().getMethod(invocation.getProxy().getMethod(), ArrayUtils.EMPTY_CLASS_ARRAY); if (action instanceof ValidationWorkflowAware) { resultName = ((ValidationWorkflowAware) action).getInputResultName(); } else if (method.isAnnotationPresent(InputConfig.class)) { InputConfig annotation = method.getAnnotation(InputConfig.class); if (StringUtils.isNotBlank(annotation.methodName())) { Method inputMethod = action.getClass().getMethod(annotation.methodName()); resultName = (String) inputMethod.invoke(action); } else { resultName = annotation.resultName(); } } else if (session.containsKey(InputResultInterceptor.INPUT_RESULT_NAME)) { resultName = (String) session.get(InputResultInterceptor.INPUT_RESULT_NAME); } } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } return resultName; }
From source file:com.doitnext.http.router.DefaultEndpointResolver.java
private void addEndpointsToResult(String pathPrefix, Class<?> classz, TreeSet<Route> routes) { RestCollection resource = classz.getAnnotation(RestCollection.class); StringBuilder pathBuilder = new StringBuilder(pathPrefix); pathBuilder.append(resource.pathprefix()); String resourcePathPrefix = pathBuilder.toString(); @SuppressWarnings("unchecked") Set<Method> methods = ReflectionUtils.getAllMethods(classz, ReflectionUtils.withAnnotation(RestMethod.class)); if (logger.isDebugEnabled()) logger.debug(String.format("Creating routes for %d methods in %s", methods.size(), classz.getName())); for (Method method : methods) { if (logger.isDebugEnabled()) logger.debug(String.format("Attempting to create route for method %s", method.getName())); RestMethod methodImpl = method.getAnnotation(RestMethod.class); pathBuilder = new StringBuilder(resourcePathPrefix); pathBuilder.append(methodImpl.template()); Object implInstance = applicationContext.getBean(resource.value(), classz); RequestResponseContext rrCtx = new RequestResponseContext( new InheritableValue(resource.requestType(), methodImpl.requestType()), new InheritableValue(resource.returnType(), methodImpl.returnType()), new InheritableValue(resource.requestFormat(), methodImpl.requestFormat()), new InheritableValue(resource.returnFormat(), methodImpl.returnFormat())); addMethodToRoutes(pathBuilder.toString(), implInstance, rrCtx, method, classz, methodImpl.method(), routes);//from ww w.java2 s . c om } // Add dump routes to the set if (endpointDumper != null) { for (String returnFormat : endpointDumper.getReturnFormats()) { pathBuilder = new StringBuilder("endpoints_"); Object implInstance = this; RequestResponseContext rrCtx = new RequestResponseContext(new InheritableValue("", ""), new InheritableValue("", ""), new InheritableValue("", ""), new InheritableValue(returnFormat, returnFormat)); try { Method method = endpointDumper.getClass().getMethod("dumpEndpoints", HttpServletRequest.class, HttpServletResponse.class); addMethodToRoutes(pathBuilder.toString(), implInstance, rrCtx, method, endpointDumper.getClass(), HttpMethod.GET, routes); } catch (SecurityException e) { logger.error("Unable to add endpoint dump", e); } catch (NoSuchMethodException e) { logger.error("Unable to add endpoint dump", e); } } } }
From source file:de.extra.client.core.annotation.PropertyPlaceholderPluginConfigurer.java
private void setPluginProperties(final ConfigurableListableBeanFactory beanFactory, final Properties properties, final String beanName, final Class<?> clazz) { final PluginConfiguration annotationConfigutation = clazz.getAnnotation(PluginConfiguration.class); final MutablePropertyValues mutablePropertyValues = beanFactory.getBeanDefinition(beanName) .getPropertyValues();/*from ww w. ja v a2s . com*/ for (final PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) { final Method setter = property.getWriteMethod(); PluginValue valueAnnotation = null; if (setter != null && setter.isAnnotationPresent(PluginValue.class)) { valueAnnotation = setter.getAnnotation(PluginValue.class); } if (valueAnnotation != null) { final String key = extractKey(annotationConfigutation, valueAnnotation, clazz); final String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK); if (StringUtils.isEmpty(value)) { throw new BeanCreationException(beanName, "No such property=[" + key + "] found in properties."); } if (LOG.isDebugEnabled()) { LOG.debug("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + key + "=" + value + "]"); } mutablePropertyValues.addPropertyValue(property.getName(), value); } } for (final Field field : clazz.getDeclaredFields()) { if (LOG.isDebugEnabled()) { LOG.debug("examining field=[" + clazz.getName() + "." + field.getName() + "]"); } if (field.isAnnotationPresent(PluginValue.class)) { final PluginValue valueAnnotation = field.getAnnotation(PluginValue.class); final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName()); if (property == null || property.getWriteMethod() == null) { throw new BeanCreationException(beanName, "setter for property=[" + clazz.getName() + "." + field.getName() + "] not available."); } final String key = extractKey(annotationConfigutation, valueAnnotation, clazz); String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK); if (value == null) { // DEFAULT Value suchen final int separatorIndex = key.indexOf(VALUE_SEPARATOR); if (separatorIndex != -1) { final String actualPlaceholder = key.substring(0, separatorIndex); final String defaultValue = key.substring(separatorIndex + VALUE_SEPARATOR.length()); value = resolvePlaceholder(actualPlaceholder, properties, SYSTEM_PROPERTIES_MODE_FALLBACK); if (value == null) { value = defaultValue; } } } if (value != null) { if (LOG.isDebugEnabled()) { LOG.debug("setting property=[" + clazz.getName() + "." + field.getName() + "] value=[" + key + "=" + value + "]"); } mutablePropertyValues.addPropertyValue(field.getName(), value); } else if (!ignoreNullValues) { throw new BeanCreationException(beanName, "No such property=[" + key + "] found in properties."); } } } }
From source file:com.iselect.kernal.pageflow.service.PageFlowServiceImpl.java
private List<RequestPath> getMethodRequestMapping(Class clazz) { List<RequestPath> requestPaths = new ArrayList<>(); for (Method method : clazz.getDeclaredMethods()) { //process RequestMapping RequestMapping mapping = method.getAnnotation(RequestMapping.class); //the method doesn't have RequestMapping annotation if (mapping == null) { continue; }/*from ww w. j av a 2s. c om*/ //process ResultTitle ResultTitle title = method.getAnnotation(ResultTitle.class); List<RequestPath> _methodPaths = buildRequestPath(clazz, mapping, title, true); requestPaths.addAll(_methodPaths); } return requestPaths; }
From source file:com.nginious.http.serialize.JsonSerializerCreator.java
/** * Returns name of property to be serialized from serializable annotation if available. Otherwise * the property name is generated from the method name. * //from ww w . j a va2s. co m * @param method * @return * @throws SerializerFactoryException */ private String getPropertyName(Method method) throws SerializerFactoryException { Serializable info = method.getAnnotation(Serializable.class); if (info != null && !info.name().equals("")) { return info.name(); } return Serialization.createPropertyNameFromMethodName(method.getName()); }
From source file:es.logongas.ix3.dao.impl.ExceptionTranslator.java
private ClassAndLabel getMethodLabel(Class clazz, String methodName) { String suffixMethodName = StringUtils.capitalize(methodName); Method method = ReflectionUtils.findMethod(clazz, "get" + suffixMethodName); if (method == null) { method = ReflectionUtils.findMethod(clazz, "is" + suffixMethodName); if (method == null) { return null; }//from w w w . j a v a2s.c om } Label label = method.getAnnotation(Label.class); if (label != null) { return new ClassAndLabel(method.getReturnType(), label.value()); } else { return new ClassAndLabel(method.getReturnType(), null); } }
From source file:cn.powerdash.libsystem.common.exception.AbstractExceptionHandler.java
private String getJsonNameFromMethod(final Field errorField, Class<?> dtoClass) { /** find annotation from get/set method........ **/ String methodName = "set" + errorField.getName().substring(0, 1).toUpperCase() + errorField.getName().substring(1); try {/* www.ja v a 2 s .co m*/ Method method = dtoClass.getDeclaredMethod(methodName, errorField.getType()); method.setAccessible(true); JsonProperty jsonProperty2 = method.getAnnotation(JsonProperty.class); if (jsonProperty2 != null) { String jp = jsonProperty2.value(); LOGGER.debug("JsonProperty from SetMethod ===== " + jp); return jp; } } catch (NoSuchMethodException e) { LOGGER.debug("NoSuchMethodException {}, try to get JsonProperty from super class", methodName); try { /** * Get JsonProperty from super class. It is only a simple implementation base on one assumption that * super class should exist this field. It does not process recursion. * **/ Method method = dtoClass.getSuperclass().getDeclaredMethod(methodName, errorField.getType()); method.setAccessible(true); JsonProperty jsonProperty2 = method.getAnnotation(JsonProperty.class); if (jsonProperty2 != null) { String jp = jsonProperty2.value(); LOGGER.debug("JsonProperty from Super {} `s SetMethod ===== {} ", dtoClass.getSuperclass(), jp); return jp; } } catch (Exception ex) { // NOSONAR LOGGER.debug(e.getMessage()); } } catch (SecurityException e) { LOGGER.debug(e.getMessage()); } return null; }