List of usage examples for java.lang.reflect Method isAnnotationPresent
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java
private static CascadeMetadata getCascadeMetadata(Method method) { final List<CascadeType> cascadeTypes = new ArrayList<CascadeType>(); if (method.isAnnotationPresent(OneToOne.class)) { cascadeTypes.addAll(Arrays.asList(method.getAnnotation(OneToOne.class).cascade())); } else if (method.isAnnotationPresent(OneToMany.class)) { cascadeTypes.addAll(Arrays.asList(method.getAnnotation(OneToMany.class).cascade())); } else if (method.isAnnotationPresent(ManyToOne.class)) { cascadeTypes.addAll(Arrays.asList(method.getAnnotation(ManyToOne.class).cascade())); } else if (method.isAnnotationPresent(ManyToMany.class)) { cascadeTypes.addAll(Arrays.asList(method.getAnnotation(ManyToMany.class).cascade())); }/*from w ww .j a v a2s .com*/ final boolean cascadeAll = cascadeTypes.contains(CascadeType.ALL); return new ImmutableCascadeMetadata(cascadeAll || cascadeTypes.contains(CascadeType.PERSIST), cascadeAll || cascadeTypes.contains(CascadeType.MERGE), cascadeAll || cascadeTypes.contains(CascadeType.REMOVE), cascadeAll || cascadeTypes.contains(CascadeType.REFRESH)); }
From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java
/** * Injects via {@link DataBoundSetter}/*from w w w . java 2s . c o m*/ */ private static void injectSetters(Object o, Map<String, ?> arguments) throws Exception { for (Class<?> c = o.getClass(); c != null; c = c.getSuperclass()) { for (Field f : c.getDeclaredFields()) { if (f.isAnnotationPresent(DataBoundSetter.class)) { f.setAccessible(true); if (arguments.containsKey(f.getName())) { Object v = arguments.get(f.getName()); f.set(o, v != null ? coerce(c.getName() + "." + f.getName(), f.getType(), v) : null); } } } for (Method m : c.getDeclaredMethods()) { if (m.isAnnotationPresent(DataBoundSetter.class)) { Type[] parameterTypes = m.getGenericParameterTypes(); if (!m.getName().startsWith("set") || parameterTypes.length != 1) { throw new IllegalStateException(m + " cannot be a @DataBoundSetter"); } m.setAccessible(true); Object[] args = buildArguments(c, arguments, parameterTypes, new String[] { Introspector.decapitalize(m.getName().substring(3)) }, false); if (args != null) { m.invoke(o, args); } } } } }
From source file:necauqua.mods.cm.asm.ASM.java
public static void init(Object holder, boolean obf) { obfuscated = obf;/*from ww w .j a v a 2s . c o m*/ loadedAtAll = true; Log.debug("Obfuscated: " + obf + ". Names will be resolved to " + (obf ? "srg" : "mcp") + " names"); for (Method m : holder.getClass().getMethods()) { if (m.isAnnotationPresent(Transformer.class)) { try { currentTransformer = m.getName(); m.invoke(holder); } catch (Exception e) { throw new IllegalStateException("Can't load transformer '" + m.getName() + "'!", e); // this should not happen } } } currentTransformer = null; }
From source file:org.jenkinsci.plugins.workflow.structs.DescribableHelper.java
/** * Computes arguments suitable to pass to {@link #instantiate} to reconstruct this object. * @param o a data-bound object/* w w w . java 2s . co m*/ * @return constructor and/or setter parameters * @throws UnsupportedOperationException if the class does not follow the expected structure */ public static Map<String, Object> uninstantiate(Object o) throws UnsupportedOperationException { Class<?> clazz = o.getClass(); Map<String, Object> r = new TreeMap<String, Object>(); String[] names; try { names = loadConstructorParamNames(clazz); } catch (NoStaplerConstructorException x) { throw new UnsupportedOperationException(x); } for (String name : names) { inspect(r, o, clazz, name); } r.values().removeAll(Collections.singleton(null)); Map<String, Object> constructorOnlyDataBoundProps = new TreeMap<String, Object>(r); List<String> dataBoundSetters = new ArrayList<String>(); for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { for (Field f : c.getDeclaredFields()) { if (f.isAnnotationPresent(DataBoundSetter.class)) { String field = f.getName(); dataBoundSetters.add(field); inspect(r, o, clazz, field); } } for (Method m : c.getDeclaredMethods()) { if (m.isAnnotationPresent(DataBoundSetter.class) && m.getName().startsWith("set")) { String field = Introspector.decapitalize(m.getName().substring(3)); dataBoundSetters.add(field); inspect(r, o, clazz, field); } } } clearDefaultSetters(clazz, r, constructorOnlyDataBoundProps, dataBoundSetters); return r; }
From source file:com.facebook.GraphObjectWrapper.java
private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) { if (hasClassBeenVerified(graphObjectClass)) { return;/*from w ww . j av a 2 s . com*/ } if (!graphObjectClass.isInterface()) { throw new FacebookGraphObjectException( "GraphObjectWrapper can only wrap interfaces, not class: " + graphObjectClass.getName()); } Method[] methods = graphObjectClass.getMethods(); for (Method method : methods) { String methodName = method.getName(); int parameterCount = method.getParameterTypes().length; Class<?> returnType = method.getReturnType(); boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class); if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) { // Don't worry about any methods from GraphObject or one of its base classes. continue; } else if (parameterCount == 1 && returnType == Void.TYPE) { if (hasPropertyNameOverride) { // If a property override is present, it MUST be valid. We don't fallback // to using the method name if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) { continue; } } else if (methodName.startsWith("set") && methodName.length() > 3) { // Looks like a valid setter continue; } } else if (parameterCount == 0 && returnType != Void.TYPE) { if (hasPropertyNameOverride) { // If a property override is present, it MUST be valid. We don't fallback // to using the method name if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) { continue; } } else if (methodName.startsWith("get") && methodName.length() > 3) { // Looks like a valid getter continue; } } throw new FacebookGraphObjectException("GraphObjectWrapper can't proxy method: " + method.toString()); } recordClassHasBeenVerified(graphObjectClass); }
From source file:me.anon.lib.Views.java
private static void inject(final Object target, Object source, Finder finder) { if (target.getClass().getDeclaredFields() != null) { ArrayList<Method> methods = new ArrayList<Method>(); ArrayList<Field> fields = new ArrayList<Field>(); Class objOrSuper = target.getClass(); if (!objOrSuper.isAnnotationPresent(Injectable.class)) { Log.e("InjectView", "No Injectable annotation for class " + objOrSuper); return; }/*from w w w.j a va 2s .c o m*/ while (objOrSuper.isAnnotationPresent(Injectable.class)) { for (Field field : objOrSuper.getDeclaredFields()) { if (field.isAnnotationPresent(InjectView.class) || field.isAnnotationPresent(InjectViews.class) || field.isAnnotationPresent(InjectFragment.class) || field.isAnnotationPresent(OnClick.class)) { fields.add(field); } } for (Method method : objOrSuper.getDeclaredMethods()) { if (method.isAnnotationPresent(OnClick.class)) { methods.add(method); } } objOrSuper = objOrSuper.getSuperclass(); } for (Field field : fields) { if (field.isAnnotationPresent(InjectView.class)) { InjectView a = (InjectView) field.getAnnotation(InjectView.class); try { field.setAccessible(true); int id = ((InjectView) a).value(); if (id < 1) { String key = ((InjectView) a).id(); if (TextUtils.isEmpty(key)) { key = field.getName(); key = key.replaceAll("(.)([A-Z])", "$1_$2").toLowerCase(Locale.ENGLISH); } Field idField = R.id.class.getField(key); id = idField.getInt(null); } View v = finder.findById(source, id); if (v != null) { field.set(target, v); } } catch (Exception e) { e.printStackTrace(); } } else if (field.isAnnotationPresent(InjectViews.class)) { try { InjectViews annotation = (InjectViews) field.getAnnotation(InjectViews.class); field.setAccessible(true); int[] ids = annotation.value(); String[] strIds = annotation.id(); Class[] instances = annotation.instances(); List<View> views = new ArrayList<View>(ids.length); if (ids.length > 0) { for (int index = 0; index < ids.length; index++) { View v = finder.findById(source, ids[index]); views.add(index, v); } } else if (strIds.length > 0) { for (int index = 0; index < ids.length; index++) { String key = annotation.id()[index]; Field idField = R.id.class.getField(key); int id = idField.getInt(null); View v = finder.findById(source, id); views.add(index, v); } } else if (instances.length > 0) { for (int index = 0; index < instances.length; index++) { List<View> v = finder.findByInstance(source, instances[index]); views.addAll(v); } } field.set(target, views); } catch (Exception e) { e.printStackTrace(); } } else if (field.isAnnotationPresent(InjectFragment.class)) { InjectFragment annotation = (InjectFragment) field.getAnnotation(InjectFragment.class); try { field.setAccessible(true); int id = ((InjectFragment) annotation).value(); Object fragment = null; if (id < 1) { String tag = ((InjectFragment) annotation).tag(); fragment = finder.findFragmentByTag(source, tag); } else { fragment = finder.findFragmentById(source, id); } if (fragment != null) { field.set(target, fragment); } } catch (Exception e) { e.printStackTrace(); } } if (field.isAnnotationPresent(OnClick.class)) { OnClick annotation = (OnClick) field.getAnnotation(OnClick.class); try { if (field.get(target) != null) { final View view = ((View) field.get(target)); if (!TextUtils.isEmpty(annotation.method())) { final String clickName = annotation.method(); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { Class<?> c = Class.forName(target.getClass().getCanonicalName()); Method m = c.getMethod(clickName, View.class); m.invoke(target, v); } catch (Exception e) { throw new IllegalArgumentException("Method not found " + clickName); } } }); } else { view.setOnClickListener((View.OnClickListener) target); } } } catch (Exception e) { e.printStackTrace(); } } } for (final Method method : methods) { if (method.isAnnotationPresent(OnClick.class)) { final OnClick annotation = (OnClick) method.getAnnotation(OnClick.class); final String clickName = method.getName(); try { int id = annotation.value(); if (id < 1) { String key = annotation.id(); if (TextUtils.isEmpty(key)) { key = clickName; key = key.replaceAll("^(on)?(.*)Click$", "$2"); key = key.replaceAll("(.)([A-Z])", "$1_$2").toLowerCase(Locale.ENGLISH); } Field field = R.id.class.getField(key); id = field.getInt(null); } View view = finder.findById(source, id); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { if (method != null && method.getParameterTypes().length > 0) { Class<?> paramType = method.getParameterTypes()[0]; method.setAccessible(true); method.invoke(target, paramType.cast(v)); } else if (method != null && method.getParameterTypes().length < 1) { method.setAccessible(true); method.invoke(target); } else { new IllegalArgumentException( "Failed to find method " + clickName + " with nil or View params") .printStackTrace(); } } catch (InvocationTargetException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } } } } }
From source file:io.stallion.reflection.PropertyUtils.java
/** * Build a map of direct javabeans properties of the target object. Only read/write properties (ie: those who have * both a getter and a setter) are returned. * @param target the target object from which to get properties names. * @return a Map of String with properties names as key and their values * @throws PropertyException if an error happened while trying to get a property. *//*from w w w .j a v a 2 s.co m*/ public static Map<String, Object> getProperties(Object target, Class<? extends Annotation>... excludeAnnotations) throws PropertyException { Map<String, Object> properties = new HashMap<String, Object>(); Class clazz = target.getClass(); Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; String name = method.getName(); Boolean hasExcludeAnno = false; if (excludeAnnotations.length > 0) { for (Class<? extends Annotation> anno : excludeAnnotations) { if (method.isAnnotationPresent(anno)) { hasExcludeAnno = true; } } } if (hasExcludeAnno) { continue; } if (method.getModifiers() == Modifier.PUBLIC && method.getParameterTypes().length == 0 && (name.startsWith("get") || name.startsWith("is")) && containsSetterForGetter(clazz, method)) { String propertyName; if (name.startsWith("get")) propertyName = Character.toLowerCase(name.charAt(3)) + name.substring(4); else if (name.startsWith("is")) propertyName = Character.toLowerCase(name.charAt(2)) + name.substring(3); else throw new PropertyException( "method '" + name + "' is not a getter, thereof no setter can be found"); try { Object propertyValue = method.invoke(target, (Object[]) null); // casting to (Object[]) b/c of javac 1.5 warning if (propertyValue != null && propertyValue instanceof Properties) { Map propertiesContent = getNestedProperties(propertyName, (Properties) propertyValue); properties.putAll(propertiesContent); } else { properties.put(propertyName, propertyValue); } } catch (IllegalAccessException ex) { throw new PropertyException("cannot set property '" + propertyName + "' - '" + name + "' is null and cannot be auto-filled", ex); } catch (InvocationTargetException ex) { throw new PropertyException("cannot set property '" + propertyName + "' - '" + name + "' is null and cannot be auto-filled", ex); } } // if } // for return properties; }
From source file:org.evosuite.setup.TestUsageChecker.java
public static boolean canUse(Method m, Class<?> ownerClass) { if (m.isBridge()) { logger.debug("Excluding bridge method: " + m.toString()); return false; }// w w w. j av a 2 s. c om if (m.isSynthetic()) { logger.debug("Excluding synthetic method: " + m.toString()); return false; } if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (Properties.hasTargetClassBeenLoaded() && !m.getDeclaringClass().equals(targetClass)) { logger.debug("Excluding deprecated method " + m.getName()); return false; } } if (m.isAnnotationPresent(Test.class) || m.isAnnotationPresent(Before.class) || m.isAnnotationPresent(BeforeClass.class) || m.isAnnotationPresent(After.class) || m.isAnnotationPresent(AfterClass.class)) { logger.debug("Excluding test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteTest.class)) { logger.debug("Excluding EvoSuite test method " + m.getName()); return false; } if (m.isAnnotationPresent(EvoSuiteExclude.class)) { logger.debug("Excluding method with exclusion annotation " + m.getName()); return false; } if (m.getDeclaringClass().equals(java.lang.Object.class)) { return false; } if (!m.getReturnType().equals(String.class) && (!canUse(m.getReturnType()) || !canUse(m.getGenericReturnType()))) { return false; } for (java.lang.reflect.Type paramType : m.getGenericParameterTypes()) { if (!canUse(paramType)) return false; } if (m.getDeclaringClass().equals(Enum.class)) { return false; /* if (m.getName().equals("valueOf") || m.getName().equals("values") || m.getName().equals("ordinal")) { logger.debug("Excluding valueOf for Enum " + m.toString()); return false; } // Skip compareTo on enums (like Randoop) if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1 && m.getParameterTypes()[0].equals(Enum.class)) return false; */ } if (m.getDeclaringClass().equals(java.lang.Thread.class)) return false; // Hashcode only if we need to cover it if (m.getName().equals("hashCode")) { final Class<?> targetClass = Properties.getTargetClassAndDontInitialise(); if (!m.getDeclaringClass().equals(targetClass)) return false; else { if (GraphPool.getInstance(ownerClass.getClassLoader()).getActualCFG(Properties.TARGET_CLASS, m.getName() + Type.getMethodDescriptor(m)) == null) { // Don't cover generated hashCode // TODO: This should work via annotations return false; } } } // Randoop special case: just clumps together a bunch of hashCodes, so skip it if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class)) return false; // Randoop special case: differs too much between JDK installations if (m.getName().equals("getAvailableLocales")) return false; if (m.getName().equals(ClassResetter.STATIC_RESET)) { logger.debug("Ignoring static reset method"); return false; } if (isForbiddenNonDeterministicCall(m)) { return false; } if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers())) { logger.debug("Ignoring static main method "); return false; } /* if(m.getTypeParameters().length > 0) { logger.debug("Cannot handle generic methods at this point"); if(m.getDeclaringClass().equals(Properties.getTargetClass())) { LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet"); } return false; } */ // If default or if (Modifier.isPublic(m.getModifiers())) { TestClusterUtils.makeAccessible(m); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(m.getModifiers())) { // && !Modifier.isProtected(m.getModifiers())) { String packageName = ClassUtils.getPackageName(ownerClass); String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) { TestClusterUtils.makeAccessible(m); return true; } } return false; }
From source file:com.github.dactiv.common.utils.ReflectionUtils.java
/** * ?methodannotationClass/*from ww w .j a va 2 s . co m*/ * * @param method * method * @param annotationClass * annotationClass * * @return {@link Annotation} */ public static <T extends Annotation> T getAnnotation(Method method, Class annotationClass) { Assert.notNull(method, "method?"); Assert.notNull(annotationClass, "annotationClass?"); method.setAccessible(true); if (method.isAnnotationPresent(annotationClass)) { return (T) method.getAnnotation(annotationClass); } return null; }
From source file:org.vulpe.commons.util.VulpeReflectUtil.java
/** * Checks if field is noted by <code>annotationClass</code>. * * @param <T>/* w ww. j a v a 2 s . c o m*/ * @param annotationClass * @param clazz * @param field * @return */ public static <T extends Annotation> T getAnnotationInField(final Class<T> annotationClass, final Class<?> clazz, final Field field) { if (field.isAnnotationPresent(annotationClass)) { return field.getAnnotation(annotationClass); } final String name = VulpeStringUtil.upperCaseFirst(field.getName()); Method method = getMethod(clazz, "get".concat(name)); if (method != null && method.isAnnotationPresent(annotationClass)) { return method.getAnnotation(annotationClass); } method = getMethod(clazz, "set".concat(name)); if (method != null && method.isAnnotationPresent(annotationClass)) { return method.getAnnotation(annotationClass); } return null; }