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

The following examples show how to use java.lang.reflect.Method#isSynthetic() . 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: SubscriberRegistry.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 2
Source File: ClassUtils.java    From katharsis-framework with 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 3
Source File: BeanInjector.java    From hop with 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 4
Source File: SubscriberRegistry.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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
Source File: ReflectionHelper.java    From drift with 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 6
Source File: SecurityManager.java    From beihu-boot with 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 7
Source File: SafeEvent.java    From AndroidPDF with 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 8
Source File: MethodDescriptor.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
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
Source File: ClassReader.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 10
Source File: ClassUtils.java    From crnk-framework with 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 11
Source File: TestSynchronization.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 12
Source File: TestSynchronization.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 13
Source File: MethodDescriptor.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 File: MethodDescriptor.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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 15
Source File: SpyVerifier.java    From appengine-plugins-core with Apache License 2.0 4 votes vote down vote up
private static boolean isPublicWithPrefix(Method method, String prefix) {
  return !method.isSynthetic()
      && Modifier.isPublic(method.getModifiers())
      && method.getName().startsWith(prefix);
}
 
Example 16
Source File: DeclaredMethodMatcher.java    From guice-validator with MIT License 4 votes vote down vote up
@Override
public boolean matches(final Method method) {
    return !method.isSynthetic() || !method.isBridge();
}
 
Example 17
Source File: PluginManager.java    From Nemisys with GNU General Public License v3.0 4 votes vote down vote up
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 18
Source File: CurieModule.java    From SciGraph with 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 File: RxBus.java    From RxBus with 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 File: ClassUtils2.java    From super-cloudops with 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)));
}