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

The following examples show how to use java.lang.reflect.Method#isSynthetic() . These examples are extracted from open source projects. 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 Project: katharsis-framework   File: ClassUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Return a list of class getters. Supports inheritance and overriding, that is when a method is found on the
 * lowest level of inheritance chain, no other method can override it. Supports inheritance and
 * doesn't return synthetic methods.
 * <p>
 * A getter:
 * <ul>
 * <li>Starts with an <i>is</i> if returns <i>boolean</i> or {@link Boolean} value</li>
 * <li>Starts with a <i>get</i> if returns non-boolean value</li>
 * </ul>
 *
 * @param beanClass class to be searched for
 * @return a list of found getters
 */
public static List<Method> getClassGetters(Class<?> beanClass) {
	Map<String, Method> result = new HashMap<>();

	Class<?> currentClass = beanClass;
	while (currentClass != null && currentClass != Object.class) {
		for (Method method : currentClass.getDeclaredMethods()) {
			if (!method.isSynthetic()) {
				if (isGetter(method)) {
					Method v = result.get(method.getName());
					if (v == null) {
						result.put(method.getName(), method);
					}
				}
			}
		}
		currentClass = currentClass.getSuperclass();
	}

	return new LinkedList<>(result.values());
}
 
Example 2
Source Project: hop   File: BeanInjector.java    License: Apache License 2.0 6 votes vote down vote up
public void runPostInjectionProcessing( Object object ) {
  Method[] methods = object.getClass().getDeclaredMethods();
  for ( Method m : methods ) {
    AfterInjection annotationAfterInjection = m.getAnnotation( AfterInjection.class );
    if ( annotationAfterInjection == null ) {
      // no after injection annotations
      continue;
    }
    if ( m.isSynthetic() || Modifier.isStatic( m.getModifiers() ) ) {
      // method is static
      throw new RuntimeException( "Wrong modifier for annotated method " + m );
    }
    try {
      m.invoke( object );
    } catch ( Exception e ) {
      throw new RuntimeException( "Can not invoke after injection method " + m, e );
    }
  }
}
 
Example 3
Source Project: drift   File: ReflectionHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Find methods that are tagged with a given annotation somewhere in the hierarchy
 */
public static Collection<Method> findAnnotatedMethods(Class<?> type, Class<? extends Annotation> annotation)
{
    List<Method> result = new ArrayList<>();

    // gather all publicly available methods
    // this returns everything, even if it's declared in a parent
    for (Method method : type.getMethods()) {
        // skip methods that are used internally by the vm for implementing covariance, etc
        if (method.isSynthetic() || method.isBridge() || isStatic(method.getModifiers())) {
            continue;
        }

        // look for annotations recursively in super-classes or interfaces
        Method managedMethod = findAnnotatedMethod(
                type,
                annotation,
                method.getName(),
                method.getParameterTypes());
        if (managedMethod != null) {
            result.add(managedMethod);
        }
    }

    return result;
}
 
Example 4
private static ImmutableList<Method> getAnnotatedMethodsNotCached(Class<?> clazz) {
  Set<? extends Class<?>> supertypes = TypeToken.of(clazz).getTypes().rawTypes();
  Map<MethodIdentifier, Method> identifiers = Maps.newHashMap();
  for (Class<?> supertype : supertypes) {
    for (Method method : supertype.getDeclaredMethods()) {
      if (method.isAnnotationPresent(Subscribe.class) && !method.isSynthetic()) {
        // TODO(cgdecker): Should check for a generic parameter type and error out
        Class<?>[] parameterTypes = method.getParameterTypes();
        checkArgument(parameterTypes.length == 1,
                      "Method %s has @Subscribe annotation but has %s parameters."
                                                         + "Subscriber methods must have exactly 1 parameter.", method, parameterTypes.length);
        MethodIdentifier ident = new MethodIdentifier(method);
        if (!identifiers.containsKey(ident)) {
          identifiers.put(ident, method);
        }
      }
    }
  }
  return ImmutableList.copyOf(identifiers.values());
}
 
Example 5
private static ImmutableList<Method> getAnnotatedMethodsNotCached(Class<?> clazz) {
  Set<? extends Class<?>> supertypes = TypeToken.of(clazz).getTypes().rawTypes();
  Map<MethodIdentifier, Method> identifiers = Maps.newHashMap();
  for (Class<?> supertype : supertypes) {
    for (Method method : supertype.getDeclaredMethods()) {
      if (method.isAnnotationPresent(Subscribe.class) && !method.isSynthetic()) {
        // TODO(cgdecker): Should check for a generic parameter type and error out
        Class<?>[] parameterTypes = method.getParameterTypes();
        checkArgument(parameterTypes.length == 1, "Method %s has @Subscribe annotation but has %s parameters."
                                                         + "Subscriber methods must have exactly 1 parameter.", method, parameterTypes.length);
        MethodIdentifier ident = new MethodIdentifier(method);
        if (!identifiers.containsKey(ident)) {
          identifiers.put(ident, method);
        }
      }
    }
  }
  return ImmutableList.copyOf(identifiers.values());
}
 
Example 6
private static Method resolve(Method oldMethod, Method newMethod) {
    if (oldMethod == null) {
        return newMethod;
    }
    if (newMethod == null) {
        return oldMethod;
    }
    return !oldMethod.isSynthetic() && newMethod.isSynthetic() ? oldMethod : newMethod;
}
 
Example 7
Source Project: beihu-boot   File: SecurityManager.java    License: Apache License 2.0 5 votes vote down vote up
private Encryptor findEncrypt(String algorithm) {

        Reflections reflections = new Reflections("ltd.beihu");

        Set<Class<?>> encryptSupportClses = reflections.getTypesAnnotatedWith(EncryptSupport.class);
        for (Class<?> encryptSupportCls : encryptSupportClses) {
            EncryptSupport encryptSupport = AnnotationUtils.findAnnotation(encryptSupportCls, EncryptSupport.class);
            String[] algorithms = encryptSupport.value();
            if (!findAlgorithm(algorithms, algorithm)) {
                continue;
            }

            Set<? extends Class<?>> supertypes = TypeToken.of(encryptSupportCls).getTypes().rawTypes();
            for (Class<?> supertype : supertypes) {
                for (Method method : supertype.getDeclaredMethods()) {
                    if (Objects.equals(encryptMethod, method.getName()) && !method.isSynthetic()) {
                        if (method.getParameterCount() < 1) {
                            logger.warn("Method {} named encrypt but has no parameters.Encrypt methods must have at least 1 parameter",
                                    ReflectionHelper.buildKey(supertype, method));
                            continue;
                        }
                        Object bean = Modifier.isStatic(method.getModifiers()) ? null : beanCache.getUnchecked(encryptSupportCls);
                        Encryptor encryptor = buildEncryptor(bean, method);
                        for (String algo : algorithms) {
                            encryptorCache.put(algo, encryptor);
                        }
                        return encryptor;
                    }
                }
            }
        }
        missingEncryptorCache.put(algorithm, true);
        throw new IllegalArgumentException("unsupported algorithm:" + algorithm);
    }
 
Example 8
private static Method resolve(Method oldMethod, Method newMethod) {
    if (oldMethod == null) {
        return newMethod;
    }
    if (newMethod == null) {
        return oldMethod;
    }
    return !oldMethod.isSynthetic() && newMethod.isSynthetic() ? oldMethod : newMethod;
}
 
Example 9
/**
 * Test all the public, unsynchronized methods of the given class. If
 * isSelfTest is true, this is a self-test to ensure that the test program
 * itself is working correctly. Should help ensure correctness of this
 * program if it changes.
 * <p/>
 * @param aClass - the class to test
 * @param isSelfTest - true if this is the special self-test class
 * @throws SecurityException
 */
private static void testClass(Class<?> aClass, boolean isSelfTest) throws
        Exception {
    // Get all unsynchronized public methods via reflection.  We don't need
    // to test synchronized methods.  By definition. they are already doing
    // the right thing.
    List<Method> methods = Arrays.asList(aClass.getDeclaredMethods());
    for (Method m : methods) {
        // skip synthetic methods, like default interface methods and lambdas
        if (m.isSynthetic()) {
            continue;
        }
        int modifiers = m.getModifiers();
        if (Modifier.isPublic(modifiers)
                && !Modifier.isSynchronized(modifiers)) {
            try {
                testMethod(aClass, m);
            } catch (TestFailedException e) {
                if (isSelfTest) {
                    String methodName = e.getMethod().getName();
                    switch (methodName) {
                        case "should_pass":
                            throw new RuntimeException(
                                    "Test failed: self-test failed.  The 'should_pass' method did not pass the synchronization test. Check the test code.");
                        case "should_fail":
                            break;
                        default:
                            throw new RuntimeException(
                                    "Test failed: something is amiss with the test. A TestFailedException was generated on a call to "
                                    + methodName + " which we didn't expect to test in the first place.");
                    }
                } else {
                    throw new RuntimeException("Test failed: the method "
                            + e.getMethod().toString()
                            + " should be synchronized, but isn't.");
                }
            }
        }
    }
}
 
Example 10
/**
 * Test all the public, unsynchronized methods of the given class. If
 * isSelfTest is true, this is a self-test to ensure that the test program
 * itself is working correctly. Should help ensure correctness of this
 * program if it changes.
 * <p/>
 * @param aClass - the class to test
 * @param isSelfTest - true if this is the special self-test class
 * @throws SecurityException
 */
private static void testClass(Class<?> aClass, boolean isSelfTest) throws
        Exception {
    // Get all unsynchronized public methods via reflection.  We don't need
    // to test synchronized methods.  By definition. they are already doing
    // the right thing.
    List<Method> methods = Arrays.asList(aClass.getDeclaredMethods());
    for (Method m : methods) {
        // skip synthetic methods, like default interface methods and lambdas
        if (m.isSynthetic()) {
            continue;
        }
        int modifiers = m.getModifiers();
        if (Modifier.isPublic(modifiers)
                && !Modifier.isSynchronized(modifiers)) {
            try {
                testMethod(aClass, m);
            } catch (TestFailedException e) {
                if (isSelfTest) {
                    String methodName = e.getMethod().getName();
                    switch (methodName) {
                        case "should_pass":
                            throw new RuntimeException(
                                    "Test failed: self-test failed.  The 'should_pass' method did not pass the synchronization test. Check the test code.");
                        case "should_fail":
                            break;
                        default:
                            throw new RuntimeException(
                                    "Test failed: something is amiss with the test. A TestFailedException was generated on a call to "
                                    + methodName + " which we didn't expect to test in the first place.");
                    }
                } else {
                    throw new RuntimeException("Test failed: the method "
                            + e.getMethod().toString()
                            + " should be synchronized, but isn't.");
                }
            }
        }
    }
}
 
Example 11
Source Project: crnk-framework   File: ClassUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static void getDeclaredClassGetters(Class<?> currentClass, Map<String, Method> resultMap,
											LinkedList<Method> results) {
	for (Method method : currentClass.getDeclaredMethods()) {
		if (!method.isSynthetic() && isGetter(method)) {
			Method v = resultMap.get(method.getName());
			if (v == null) {
				resultMap.put(method.getName(), method);
				results.add(method);
			}
		}
	}
}
 
Example 12
public static long getMemberFlag(Method member){
    int flag=member.getModifiers();
    if(member.isSynthetic()) flag|=SYNTHETIC;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N&&member.isDefault()) {
        flag|=DEFAULT;
    }
    if(member.isBridge()) flag|=BRIDGE;
    if(member.isVarArgs()) flag|=VARARGS;
    return flag;
}
 
Example 13
private static Method resolve(Method oldMethod, Method newMethod) {
    if (oldMethod == null) {
        return newMethod;
    }
    if (newMethod == null) {
        return oldMethod;
    }
    return !oldMethod.isSynthetic() && newMethod.isSynthetic() ? oldMethod : newMethod;
}
 
Example 14
Source Project: AndroidPDF   File: SafeEvent.java    License: Apache License 2.0 5 votes vote down vote up
private Class<?> getListenerType()
{
    for (Method method : getClass().getMethods())
    {
        if ("dispatchSafely".equals(method.getName()) && !method.isSynthetic())
        {
            return method.getParameterTypes()[0];
        }
    }
    throw new RuntimeException("Couldn't find dispatchSafely method");
}
 
Example 15
public void registerEvents(Listener listener, Plugin plugin) {
    if (!plugin.isEnabled()) {
        throw new PluginException("Plugin attempted to register " + listener.getClass().getName() + " while not enabled");
    }

    Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<>();
    Set<Method> methods;
    try {
        Method[] publicMethods = listener.getClass().getMethods();
        Method[] privateMethods = listener.getClass().getDeclaredMethods();
        methods = new HashSet<>(publicMethods.length + privateMethods.length, 1.0f);
        Collections.addAll(methods, publicMethods);
        Collections.addAll(methods, privateMethods);
    } catch (NoClassDefFoundError e) {
        plugin.getLogger().error("Plugin " + plugin.getDescription().getFullName() + " has failed to register events for " + listener.getClass() + " because " + e.getMessage() + " does not exist.");
        return;
    }

    for (final Method method : methods) {
        final EventHandler eh = method.getAnnotation(EventHandler.class);
        if (eh == null) continue;
        if (method.isBridge() || method.isSynthetic()) {
            continue;
        }
        final Class<?> checkClass;

        if (method.getParameterTypes().length != 1 || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
            plugin.getLogger().error(plugin.getDescription().getFullName() + " attempted to register an invalid EventHandler method signature \"" + method.toGenericString() + "\" in " + listener.getClass());
            continue;
        }

        final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
        method.setAccessible(true);
        Set<RegisteredListener> eventSet = ret.get(eventClass);
        if (eventSet == null) {
            eventSet = new HashSet<>();
            ret.put(eventClass, eventSet);
        }

        for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
            // This loop checks for extending deprecated events
            if (clazz.getAnnotation(Deprecated.class) != null) {
                if (Boolean.valueOf(String.valueOf(this.server.getConfig("settings.deprecated-verbpse", true)))) {
                    this.server.getLogger().warning(this.server.getLanguage().translateString("nemisys.plugin.deprecatedEvent", new String[]{plugin.getName(), clazz.getName(), listener.getClass().getName() + "." + method.getName() + "()"}));
                }
                break;
            }
        }
        this.registerEvent(eventClass, listener, eh.priority(), new MethodEventExecutor(method), plugin, eh.ignoreCancelled());
    }
}
 
Example 16
Source Project: guice-validator   File: DeclaredMethodMatcher.java    License: MIT License 4 votes vote down vote up
@Override
public boolean matches(final Method method) {
    return !method.isSynthetic() || !method.isBridge();
}
 
Example 17
private static boolean isPublicWithPrefix(Method method, String prefix) {
  return !method.isSynthetic()
      && Modifier.isPublic(method.getModifiers())
      && method.getName().startsWith(prefix);
}
 
Example 18
Source Project: SciGraph   File: CurieModule.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public boolean matches(final Method method) {
  return method.isAnnotationPresent(AddCuries.class) && !method.isSynthetic();
}
 
Example 19
Source Project: RxBus   File: RxBus.java    License: Apache License 2.0 2 votes vote down vote up
public void register(@NonNull Object observer) {
    ObjectHelper.requireNonNull(observer, "Observer to register must not be null.");

    Class<?> observerClass = observer.getClass();

    if (OBSERVERS.putIfAbsent(observerClass, new CompositeDisposable()) != null)
        throw new IllegalArgumentException("Observer has already been registered.");

    CompositeDisposable composite = OBSERVERS.get(observerClass);

    Set<Class<?>> events = new HashSet<>();

    for (Method method : observerClass.getDeclaredMethods()) {

        if (method.isBridge() || method.isSynthetic())
            continue;

        if (!method.isAnnotationPresent(Subscribe.class))
            continue;

        int mod = method.getModifiers();

        if (Modifier.isStatic(mod) || !Modifier.isPublic(mod))
            throw new IllegalArgumentException("Method " + method.getName() +
                    " has @Subscribe annotation must be public, non-static");

        Class<?>[] params = method.getParameterTypes();

        if (params.length != 1)
            throw new IllegalArgumentException("Method " + method.getName() +
                    " has @Subscribe annotation must require a single argument");

        Class<?> eventClass = params[0];

        if (eventClass.isInterface())
            throw new IllegalArgumentException("Event class must be on a concrete class type.");

        if (!events.add(eventClass))
            throw new IllegalArgumentException("Subscriber for " + eventClass.getSimpleName() +
                    " has already been registered.");

        composite.add(bus.ofType(eventClass)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new AnnotatedSubscriber<>(observer, method)));
    }

}
 
Example 20
Source Project: super-cloudops   File: ClassUtils2.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Determine whether the given method is declared by the user or at least
 * pointing to a user-declared method.
 * <p>
 * Checks {@link Method#isSynthetic()} (for implementation methods) as well
 * as the {@code GroovyObject} interface (for interface methods; on an
 * implementation class, implementations of the {@code GroovyObject} methods
 * will be marked as synthetic anyway). Note that, despite being synthetic,
 * bridge methods ({@link Method#isBridge()}) are considered as user-level
 * methods since they are eventually pointing to a user-declared generic
 * method.
 * 
 * @param method
 *            the method to check
 * @return {@code true} if the method can be considered as user-declared;
 *         [@code false} otherwise
 */
public static boolean isUserLevelMethod(Method method) {
	Assert2.notNull(method, "Method must not be null");
	return (method.isBridge() || (!method.isSynthetic() && !isGroovyObjectMethod(method)));
}