List of usage examples for java.lang.reflect Method getAnnotation
public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
From source file:com.predic8.membrane.annot.bean.MCUtil.java
private static void addXML(Object object, String id, XMLStreamWriter xew, SerializationContext sc) throws XMLStreamException { if (object == null) throw new InvalidParameterException("'object' must not be null."); Class<? extends Object> clazz = object.getClass(); MCElement e = clazz.getAnnotation(MCElement.class); if (e == null) throw new IllegalArgumentException("'object' must be @MCElement-annotated."); BeanWrapperImpl src = new BeanWrapperImpl(object); xew.writeStartElement(e.name());//from ww w . ja v a 2 s . c om if (id != null) xew.writeAttribute("id", id); HashSet<String> attributes = new HashSet<String>(); for (Method m : clazz.getMethods()) { if (!m.getName().startsWith("set")) continue; String propertyName = AnnotUtils.dejavaify(m.getName().substring(3)); MCAttribute a = m.getAnnotation(MCAttribute.class); if (a != null) { Object value = src.getPropertyValue(propertyName); String str; if (value == null) continue; else if (value instanceof String) str = (String) value; else if (value instanceof Boolean) str = ((Boolean) value).toString(); else if (value instanceof Integer) str = ((Integer) value).toString(); else if (value instanceof Long) str = ((Long) value).toString(); else if (value instanceof Enum<?>) str = value.toString(); else { MCElement el = value.getClass().getAnnotation(MCElement.class); if (el != null) { str = defineBean(sc, value, null, true); } else { str = "?"; sc.incomplete = true; } } if (a.attributeName().length() > 0) propertyName = a.attributeName(); attributes.add(propertyName); xew.writeAttribute(propertyName, str); } } for (Method m : clazz.getMethods()) { if (!m.getName().startsWith("set")) continue; String propertyName = AnnotUtils.dejavaify(m.getName().substring(3)); MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class); if (o != null) { Object value = src.getPropertyValue(propertyName); if (value instanceof Map<?, ?>) { Map<?, ?> map = (Map<?, ?>) value; for (Map.Entry<?, ?> entry : map.entrySet()) { Object key = entry.getKey(); Object val = entry.getValue(); if (!(key instanceof String) || !(val instanceof String)) { sc.incomplete = true; key = "incompleteAttributes"; val = "?"; } if (attributes.contains(key)) continue; attributes.add((String) key); xew.writeAttribute((String) key, (String) val); } } else { xew.writeAttribute("incompleteAttributes", "?"); sc.incomplete = true; } } } List<Method> childElements = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (!m.getName().startsWith("set")) continue; String propertyName = AnnotUtils.dejavaify(m.getName().substring(3)); MCChildElement c = m.getAnnotation(MCChildElement.class); if (c != null) { childElements.add(m); } MCTextContent t = m.getAnnotation(MCTextContent.class); if (t != null) { Object value = src.getPropertyValue(propertyName); if (value == null) { continue; } else if (value instanceof String) { xew.writeCharacters((String) value); } else { xew.writeCharacters("?"); sc.incomplete = true; } } } Collections.sort(childElements, new Comparator<Method>() { @Override public int compare(Method o1, Method o2) { MCChildElement c1 = o1.getAnnotation(MCChildElement.class); MCChildElement c2 = o2.getAnnotation(MCChildElement.class); return c1.order() - c2.order(); } }); for (Method m : childElements) { String propertyName = AnnotUtils.dejavaify(m.getName().substring(3)); Object value = src.getPropertyValue(propertyName); if (value != null) { if (value instanceof Collection<?>) { for (Object item : (Collection<?>) value) addXML(item, null, xew, sc); } else { addXML(value, null, xew, sc); } } } xew.writeEndElement(); }
From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java
/** * Parse information for a given controller. * /*from www . j a v a 2s. c o m*/ * @param controller * @param resourcesFolder * @return * @throws SiteWhereException */ protected static ParsedController parseController(Class<?> controller, File resourcesFolder) throws SiteWhereException { ParsedController parsed = new ParsedController(); Api api = controller.getAnnotation(Api.class); if (api == null) { throw new SiteWhereException("Swagger Api annotation missing on documented controller."); } parsed.setResource(api.value()); DocumentedController doc = controller.getAnnotation(DocumentedController.class); parsed.setName(doc.name()); parsed.setGlobal(doc.global()); System.out.println("Processing controller: " + parsed.getName() + " (" + parsed.getResource() + ")"); RequestMapping mapping = controller.getAnnotation(RequestMapping.class); if (mapping == null) { throw new SiteWhereException( "Spring RequestMapping annotation missing on documented controller: " + controller.getName()); } parsed.setBaseUri("/sitewhere/api" + mapping.value()[0]); // Verify controller markdown file. File markdownFile = new File(resourcesFolder, parsed.getResource() + ".md"); if (!markdownFile.exists()) { throw new SiteWhereException("Controller markdown file missing: " + markdownFile.getAbsolutePath()); } // Verify controller resources folder. File resources = new File(resourcesFolder, parsed.getResource()); if (!resources.exists()) { throw new SiteWhereException("Controller markdown folder missing: " + resources.getAbsolutePath()); } try { PegDownProcessor processor = new PegDownProcessor(); String markdown = readFile(markdownFile); parsed.setDescription(processor.markdownToHtml(markdown)); } catch (IOException e) { throw new SiteWhereException("Unable to read markdown from: " + markdownFile.getAbsolutePath(), e); } Method[] methods = controller.getMethods(); for (Method method : methods) { if (method.getAnnotation(Documented.class) != null) { ParsedMethod parsedMethod = parseMethod(parsed.getBaseUri(), method, resources); parsed.getMethods().add(parsedMethod); } } Collections.sort(parsed.getMethods(), new Comparator<ParsedMethod>() { @Override public int compare(ParsedMethod o1, ParsedMethod o2) { return o1.getSummary().compareTo(o2.getSummary()); } }); return parsed; }
From source file:com.zc.util.refelect.Reflector.java
/** * ?methodannotationClass/*w w w.j a v a 2s . 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:com.eucalyptus.upgrade.TestHarness.java
@SuppressWarnings("unchecked") private static Multimap<Class, Method> getTestMethods() throws Exception { final Multimap<Class, Method> testMethods = ArrayListMultimap.create(); List<Class> classList = Lists.newArrayList(); for (File f : new File(System.getProperty("euca.home") + "/usr/share/eucalyptus").listFiles()) { if (f.getName().startsWith("eucalyptus") && f.getName().endsWith(".jar") && !f.getName().matches(".*-ext-.*")) { try { JarFile jar = new JarFile(f); Enumeration<JarEntry> jarList = jar.entries(); for (JarEntry j : Collections.list(jar.entries())) { if (j.getName().matches(".*\\.class.{0,1}")) { String classGuess = j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", ""); try { Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess); for (final Method m : candidate.getDeclaredMethods()) { if (Iterables.any(testAnnotations, new Predicate<Class<? extends Annotation>>() { public boolean apply(Class<? extends Annotation> arg0) { return m.getAnnotation(arg0) != null; } })) { System.out.println("Added test class: " + candidate.getCanonicalName()); testMethods.put(candidate, m); }/*from w w w . j a v a2s.c o m*/ } } catch (ClassNotFoundException e) { } } } jar.close(); } catch (Exception e) { System.out.println(e.getMessage()); continue; } } } return testMethods; }
From source file:airlift.util.AirliftUtil.java
/** * Gets the method annotation./* ww w. ja va 2s. c o m*/ * * @param <T> the generic type * @param _class the _class * @param _attributeName the _attribute name * @param _annotationClass the _annotation class * @return the method annotation */ public static <T extends Annotation> T getMethodAnnotation(Class _class, String _attributeName, Class<T> _annotationClass) { try { String getter = "get" + upperTheFirstCharacter(_attributeName); java.lang.reflect.Method method = _class.getMethod(getter); return method.getAnnotation(_annotationClass); } catch (Throwable t) { throw new RuntimeException(t); } }
From source file:ch.flashcard.HibernateDetachUtility.java
private static void nullOutFieldsByAccessors(Object value, Map<Integer, Object> checkedObjects, Map<Integer, List<Object>> checkedObjectCollisionMap, int depth, SerializationType serializationType) throws Exception { // Null out any collections that aren't loaded BeanInfo bi = Introspector.getBeanInfo(value.getClass(), Object.class); PropertyDescriptor[] pds = bi.getPropertyDescriptors(); for (PropertyDescriptor pd : pds) { Object propertyValue = null; try {//from w ww . j av a 2 s . c om propertyValue = pd.getReadMethod().invoke(value); } catch (Throwable lie) { if (LOG.isDebugEnabled()) { LOG.debug("Couldn't load: " + pd.getName() + " off of " + value.getClass().getSimpleName(), lie); } } if (!Hibernate.isInitialized(propertyValue)) { try { if (LOG.isDebugEnabled()) { LOG.debug("Nulling out: " + pd.getName() + " off of " + value.getClass().getSimpleName()); } Method writeMethod = pd.getWriteMethod(); if ((writeMethod != null) && (writeMethod.getAnnotation(XmlTransient.class) == null)) { pd.getWriteMethod().invoke(value, new Object[] { null }); } else { nullOutField(value, pd.getName()); } } catch (Exception lie) { LOG.debug("Couldn't null out: " + pd.getName() + " off of " + value.getClass().getSimpleName() + " trying field access", lie); nullOutField(value, pd.getName()); } } else { if ((propertyValue instanceof Collection) || ((propertyValue != null) && propertyValue.getClass().getName().startsWith("org.rhq.core.domain"))) { nullOutUninitializedFields(propertyValue, checkedObjects, checkedObjectCollisionMap, depth + 1, serializationType); } } } }
From source file:com.netflix.iep.config.Configuration.java
@SuppressWarnings("unchecked") public static <T> T newProxy(final Class<T> ctype, final String prefix) { InvocationHandler handler = new InvocationHandler() { @Override/*from ww w. j a va 2s . com*/ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("get")) { return iConfiguration.get((args[0] == null) ? null : args[0].toString()); } else { Class rt = method.getReturnType(); String key = (prefix == null) ? method.getName() : prefix + "." + method.getName(); if (IConfiguration.class.isAssignableFrom(rt)) { return newProxy(rt, key); } else { String value = iConfiguration.get(key); if (value == null) { DefaultValue anno = method.getAnnotation(DefaultValue.class); value = (anno == null) ? null : anno.value(); } if (value == null) { if (rt.isPrimitive()) throw new IllegalStateException("no value for property " + method.getName()); return null; } return Strings.cast(rt, value); } } } }; return (T) Proxy.newProxyInstance(ctype.getClassLoader(), new Class[] { ctype }, handler); }
From source file:com.sitewhere.web.rest.documentation.RestDocumentationGenerator.java
/** * Parse examples for method.// w ww . ja va 2s.c o m * * @param method * @param parsed * @param resources * @throws SiteWhereException */ protected static void parseExamples(Method method, ParsedMethod parsedMethod, File resources) throws SiteWhereException { Documented documented = method.getAnnotation(Documented.class); Example[] examples = documented.examples(); File examplesResources = new File(resources, "examples"); for (Example example : examples) { ParsedExample parsed = new ParsedExample(); String mdFilename = example.description(); if (mdFilename != null) { File markdownFile = new File(examplesResources, mdFilename); if (markdownFile.exists()) { PegDownProcessor processor = new PegDownProcessor(); String markdown = readFile(markdownFile); parsed.setDescription(processor.markdownToHtml(markdown)); } } Class<?> jsonObj = example.json(); if (jsonObj != null) { try { Object instance = jsonObj.newInstance(); try { Method generate = jsonObj.getMethod("generate"); instance = generate.invoke(instance); } catch (NoSuchMethodException e) { // Fall through if method is not implemented. } catch (SecurityException e) { throw new SiteWhereException("Error executing generator method.", e); } catch (IllegalArgumentException e) { throw new SiteWhereException("Error executing generator method.", e); } catch (InvocationTargetException e) { throw new SiteWhereException("Error executing generator method.", e); } String marshaled = MarshalUtils.marshalJsonAsPrettyString(instance); parsed.setJson(marshaled); } catch (InstantiationException e) { throw new SiteWhereException("Unable to create instance of JSON example object.", e); } catch (IllegalAccessException e) { throw new SiteWhereException("Unable to create instance of JSON example object.", e); } } parsed.setStage(example.stage()); parsedMethod.getExamples().add(parsed); } }
From source file:es.logongas.ix3.util.ReflectionUtil.java
static private <T extends Annotation> T getMethodAnnotation(Class baseClass, String methodName, Class<T> annotationClass) { String suffixMethodName = StringUtils.capitalize(methodName); Method method = getMethod(baseClass, "get" + suffixMethodName); if (method == null) { method = getMethod(baseClass, "is" + suffixMethodName); if (method == null) { method = getMethod(baseClass, methodName); if (method == null) { return null; }/*from w w w . j a va 2 s.c o m*/ } } T annotation = method.getAnnotation(annotationClass); return annotation; }
From source file:com.l2jfree.gameserver.model.restriction.global.GlobalRestrictions.java
public synchronized static void activate(GlobalRestriction restriction) { for (Method method : restriction.getClass().getMethods()) { RestrictionMode mode = RestrictionMode.parse(method); if (mode == null) continue; if (method.getAnnotation(DisabledRestriction.class) != null) continue; GlobalRestriction[] restrictions = _restrictions[mode.ordinal()]; if (!ArrayUtils.contains(restrictions, restriction)) restrictions = ArrayUtils.add(restrictions, restriction); Arrays.sort(restrictions, mode); _restrictions[mode.ordinal()] = restrictions; }// w w w . ja v a2 s . co m }