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

The following are Jave code examples for showing how to use isSynthetic() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: aws-sdk-java-v2   File: StandardBeanProperties.java   View Source Code Vote up 6 votes
private boolean canMap(Method method, boolean inherited) {
    if (method.getName().matches("^(get|is).+") == false) {
        return false;
    } else if (method.getParameterTypes().length != 0) {
        return false;
    } else if (method.isBridge() || method.isSynthetic()) {
        return false;
    } else if (method.getDeclaringClass() == Object.class) {
        return false;
    } else if (!inherited && method.getDeclaringClass() != this.clazz &&
               StandardAnnotationMaps.of(method.getDeclaringClass()).attributeType() == null) {
        return false;
    } else {
        return true;
    }
}
 
Example 2
Project: drift   File: ReflectionHelper.java   View Source Code Vote up 6 votes
/**
 * 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 3
Project: guava-mock   File: SubscriberRegistry.java   View Source Code Vote up 6 votes
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 4
Project: guava-mock   File: NullPointerTester.java   View Source Code Vote up 6 votes
private ImmutableList<Method> getVisibleMethods(Class<?> cls) {
  // Don't use cls.getPackage() because it does nasty things like reading
  // a file.
  String visiblePackage = Reflection.getPackageName(cls);
  ImmutableList.Builder<Method> builder = ImmutableList.builder();
  for (Class<?> type : TypeToken.of(cls).getTypes().rawTypes()) {
    if (!Reflection.getPackageName(type).equals(visiblePackage)) {
      break;
    }
    for (Method method : type.getDeclaredMethods()) {
      if (!method.isSynthetic() && isVisible(method)) {
        builder.add(method);
      }
    }
  }
  return builder.build();
}
 
Example 5
Project: businessworks   File: ProviderMethodsModule.java   View Source Code Vote up 6 votes
/**
 * Returns true if the method is a provider.
 *
 * Synthetic bridge methods are excluded. Starting with JDK 8, javac copies annotations onto
 * bridge methods (which always have erased signatures).
 */
private Optional<Annotation> isProvider(Binder binder, Method method) {
  if (method.isBridge() || method.isSynthetic()) {
    return Optional.absent();
  }
  Annotation annotation = null;
  for (Class<? extends Annotation> annotationClass : scanner.annotationClasses()) {
    Annotation foundAnnotation = method.getAnnotation(annotationClass);
    if (foundAnnotation != null) {
      if (annotation != null) {
        binder.addError("More than one annotation claimed by %s on method %s."
            + " Methods can only have one annotation claimed per scanner.",
            scanner, method);
        return Optional.absent();
      }
      annotation = foundAnnotation;
    }
  }
  return Optional.fromNullable(annotation);
}
 
Example 6
Project: Reer   File: ModelSchemaUtils.java   View Source Code Vote up 5 votes
private static boolean isIgnoredMethod(Method method) {
    int modifiers = method.getModifiers();
    if (method.isSynthetic() || Modifier.isStatic(modifiers)) {
        return true;
    }

    // Ignore overrides of Object and GroovyObject methods
    return GroovyMethods.isObjectMethod(method);
}
 
Example 7
Project: openjdk-jdk10   File: PrivateLambdas.java   View Source Code Vote up 5 votes
public static void main(String[] args) throws Exception {

      // Check that all the lambda methods are private instance synthetic
      for (Class<?> k : new Class<?>[] { A.class, B.class, C.class }) {
         Method[] methods = k.getDeclaredMethods();
         int lambdaCount = 0;
         for(Method m : methods) {
            if (m.getName().startsWith("lambda$")) {
               ++lambdaCount;
               int mod = m.getModifiers();
               if ((mod & Modifier.PRIVATE) == 0) {
                  throw new Exception("Expected " + m + " to be private");
               }
               if (!m.isSynthetic()) {
                  throw new Exception("Expected " + m + " to be synthetic");
               }
               if ((mod & Modifier.STATIC) != 0) {
                  throw new Exception("Expected " + m + " to be instance method");
               }
            }
         }
         if (lambdaCount == 0) {
            throw new Exception("Expected at least one lambda method");
         }
      }

      /*
       * Unless the lambda methods are private, this will fail with:
       *  AbstractMethodError:
       *        Conflicting default methods: A.lambda$0 B.lambda$0 C.lambda$0
       */
      X x = new PrivateLambdas();
      if (!x.name().equals(" A B C")) {
         throw new Exception("Expected ' A B C' got: " + x.name());
      }
   }
 
Example 8
Project: mug   File: MaybeTest.java   View Source Code Vote up 5 votes
@Test public void testNulls_staticMethods() {
  for (Method method : Maybe.class.getMethods()) {
    if (method.isSynthetic()) continue;
    if (method.getName().equals("of")) continue;
    if (Modifier.isStatic(method.getModifiers())) {
      new NullPointerTester().testMethod(null, method);
    }
  }
}
 
Example 9
Project: openjdk-jdk10   File: TestResolvedJavaField.java   View Source Code Vote up 5 votes
/**
 * Ensures that any new methods added to {@link ResolvedJavaMethod} either have a test written
 * for them or are added to {@link #untestedApiMethods}.
 */
@Test
public void testCoverage() {
    Set<String> known = new HashSet<>(Arrays.asList(untestedApiMethods));
    for (Method m : ResolvedJavaField.class.getDeclaredMethods()) {
        if (m.isSynthetic()) {
            continue;
        }
        if (findTestMethod(m) == null) {
            assertTrue("test missing for " + m, known.contains(m.getName()));
        } else {
            assertFalse("test should be removed from untestedApiMethods" + m, known.contains(m.getName()));
        }
    }
}
 
Example 10
Project: crnk-framework   File: ClassUtils.java   View Source Code Vote up 5 votes
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
Project: openjdk-jdk10   File: TestSynchronization.java   View Source Code Vote up 5 votes
/**
 * 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
Project: Reer   File: ModelRuleExtractor.java   View Source Code Vote up 4 votes
private void validateNonRuleMethod(Method method, RuleSourceValidationProblemCollector problems) {
    if (!Modifier.isPrivate(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && !method.isSynthetic() && !GroovyMethods.isObjectMethod(method)) {
        problems.add(method, "A method that is not annotated as a rule must be private");
    }
}
 
Example 13
Project: Nukkit-Java9   File: PluginManager.java   View Source Code Vote up 4 votes
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);

        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("nukkit.plugin.deprecatedEvent", plugin.getName(), clazz.getName(), listener.getClass().getName() + "." + method.getName() + "()"));
                }
                break;
            }
        }
        this.registerEvent(eventClass, listener, eh.priority(), new MethodEventExecutor(method), plugin, eh.ignoreCancelled());
    }
}
 
Example 14
Project: CoreX   File: PluginManager.java   View Source Code Vote up 4 votes
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);

        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("nukkit.plugin.deprecatedEvent", plugin.getName(), clazz.getName(), listener.getClass().getName() + "." + method.getName() + "()"));
                }
                break;
            }
        }
        EventExecutor executor = EventExecutor.create(method, eventClass);
        this.registerEvent(eventClass, listener, eh.priority(), executor, plugin, eh.ignoreCancelled());
    }
}
 
Example 15
Project: Equella   File: TransactionModule.java   View Source Code Vote up 4 votes
@Override
public boolean matches(Method t)
{
	return !t.isSynthetic() && t.isAnnotationPresent(Transactional.class);
}
 
Example 16
Project: Jenisys3   File: PluginManager.java   View Source Code Vote up 4 votes
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);

        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("nukkit.plugin.deprecatedEvent", plugin.getName(), clazz.getName(), listener.getClass().getName() + "." + method.getName() + "()"));
                }
                break;
            }
        }
        this.registerEvent(eventClass, listener, eh.priority(), new MethodEventExecutor(method), plugin, eh.ignoreCancelled());
    }
}
 
Example 17
Project: Jupiter   File: PluginManager.java   View Source Code Vote up 4 votes
public void registerEvents(Listener listener, Plugin plugin) {
    if (!plugin.isEnabled()) {
        throw new PluginException("Plugin attempted to register " + listener.getClass().getName() + " while not enabled");
    }

    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);

        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("nukkit.plugin.deprecatedEvent", plugin.getName(), clazz.getName(), listener.getClass().getName() + "." + method.getName() + "()"));
                }
                break;
            }
        }
        this.registerEvent(eventClass, listener, eh.priority(), new MethodEventExecutor(method), plugin, eh.ignoreCancelled());
    }
}
 
Example 18
Project: jDialects   File: ClassUtils.java   View Source Code Vote up 2 votes
/**
 * 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) {
	Assert.notNull(method, "Method must not be null");
	return (method.isBridge() || (!method.isSynthetic() && !isGroovyObjectMethod(method)));
}
 
Example 19
Project: util   File: ClassUtils.java   View Source Code Vote up 2 votes
/**
 * 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) {
	Assert.notNull(method, "Method must not be null");
	return (method.isBridge() || (!method.isSynthetic() && !isGroovyObjectMethod(method)));
}
 
Example 20
Project: businessworks   File: InjectionPoint.java   View Source Code Vote up 2 votes
/** 
 * Returns true if the method is eligible to be injected.  This is different than
 * {@link #isValidMethod}, because ineligibility will not drop a method
 * from being injected if a superclass was eligible & valid. 
 * Bridge & synthetic methods are excluded from eligibility for two reasons:
 * 
 * <p>Prior to Java8, javac would generate these methods in subclasses without
 * annotations, which means this would accidentally stop injecting a method
 * annotated with {@link javax.inject.Inject}, since the spec says to stop
 * injecting if a subclass isn't annotated with it.
 * 
 * <p>Starting at Java8, javac copies the annotations to the generated subclass
 * method, except it leaves out the generic types.  If this considered it a valid
 * injectable method, this would eject the parent's overridden method that had the
 * proper generic types, and would use invalid injectable parameters as a result.
 * 
 * <p>The fix for both is simply to ignore these synthetic bridge methods.
 */
private static boolean isEligibleForInjection(Method method, boolean statics) {
  return Modifier.isStatic(method.getModifiers()) == statics
      && !method.isBridge()
      && !method.isSynthetic();
}