Example usage for java.lang Class getModifiers

List of usage examples for java.lang Class getModifiers

Introduction

In this page you can find the example usage for java.lang Class getModifiers.

Prototype

@HotSpotIntrinsicCandidate
public native int getModifiers();

Source Link

Document

Returns the Java language modifiers for this class or interface, encoded in an integer.

Usage

From source file:javadz.beanutils.MethodUtils.java

/**
 * <p>Return an accessible method (that is, one that can be invoked via
 * reflection) by scanning through the superclasses. If no such method
 * can be found, return <code>null</code>.</p>
 *
 * @param clazz Class to be checked/*from w w w  .  ja v a2 s .  c  om*/
 * @param methodName Method name of the method we wish to call
 * @param parameterTypes The parameter type signatures
 */
private static Method getAccessibleMethodFromSuperclass(Class clazz, String methodName,
        Class[] parameterTypes) {

    Class parentClazz = clazz.getSuperclass();
    while (parentClazz != null) {
        if (Modifier.isPublic(parentClazz.getModifiers())) {
            try {
                return parentClazz.getMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                return null;
            }
        }
        parentClazz = parentClazz.getSuperclass();
    }
    return null;
}

From source file:bboss.org.apache.velocity.util.introspection.ClassMap.java

private void populateMethodCacheWithInterface(MethodCache methodCache, Class iface) {
    if (Modifier.isPublic(iface.getModifiers())) {
        populateMethodCacheWith(methodCache, iface);
    }//from   ww  w .  j  ava 2  s  . c om
    Class[] supers = iface.getInterfaces();
    for (int i = 0; i < supers.length; i++) {
        populateMethodCacheWithInterface(methodCache, supers[i]);
    }
}

From source file:org.impalaframework.command.basic.ModuleDefinitionAwareClassFilter.java

public boolean accept(File pathname) {
    if (!super.accept(pathname)) {
        return false;
    }/*  ww  w. j  av a  2  s  .c  o  m*/

    if (pathname.isDirectory()) {
        return true;
    }

    if (rootCanonicalPath == null) {
        throw new ConfigurationException("root canonical path not set");
    }

    String canonicalPath = null;
    try {
        canonicalPath = pathname.getCanonicalPath();
    } catch (IOException e) {
        logger.error("Could not read canonical path for " + pathname, e);
        return false;
    }
    String relativePath = canonicalPath.substring(rootCanonicalPath.length());

    relativePath = relativePath.replace(File.separator, ".");
    relativePath = relativePath.replace("/", ".");
    relativePath = relativePath.substring(0, relativePath.length() - ".class".length());
    if (relativePath.startsWith(".")) {
        relativePath = relativePath.substring(1);
    }

    //create a classloader pointing to the supplied root file location
    ModuleClassLoader classLoader = new ModuleClassLoader(new File[] { this.rootFile });

    Class<?> forName = null;
    try {
        forName = Class.forName(relativePath, false, classLoader);
        if (forName.isInterface()) {
            return false;
        }

        int mods = forName.getModifiers();
        if (Modifier.isAbstract(mods)) {
            return false;
        }

        if (ModuleDefinitionSource.class.isAssignableFrom(forName)) {
            return true;
        }
    } catch (ClassNotFoundException e) {
        logger.error("Unable to resolve class associated with path " + pathname, e);
    }

    return false;

}

From source file:net.udidb.engine.ops.impls.help.HelpMessageProvider.java

@Inject
public HelpMessageProvider(@Named("OP_PACKAGES") String[] opPackages) {

    Set<URL> packages = new HashSet<>();
    for (String opPackage : opPackages) {
        packages.addAll(ClasspathHelper.forPackage(opPackage));
    }//from ww w.j a v a2s .c  o  m
    Reflections reflections = new Reflections(packages, new SubTypesScanner());
    for (Class<? extends Operation> opClass : reflections.getSubTypesOf(Operation.class)) {
        if (Modifier.isAbstract(opClass.getModifiers()))
            continue;

        HelpMessage[] helpMessages = opClass.getAnnotationsByType(HelpMessage.class);
        DisplayName displayName = opClass.getAnnotation(DisplayName.class);

        if (helpMessages.length == 0 || displayName == null) {
            throw new RuntimeException(opClass.getSimpleName() + " is an invalid Operation");
        }

        String name = displayName.value();

        HelpMessageDescriptor descriptor = new HelpMessageDescriptor();

        descriptor.global = opClass.isAnnotationPresent(GlobalOperation.class);
        descriptor.shortMessage = selectMessage(helpMessages);
        descriptor.longMessage = createLongMessage(name, descriptor.shortMessage, opClass);

        helpMessageDescriptors.put(name, descriptor);
    }
}

From source file:ca.uhn.fhir.rest.method.HistoryMethodBinding.java

public HistoryMethodBinding(Method theMethod, FhirContext theContext, Object theProvider) {
    super(toReturnType(theMethod, theProvider), theMethod, theContext, theProvider);

    myIdParamIndex = MethodUtil.findIdParameterIndex(theMethod, getContext());

    History historyAnnotation = theMethod.getAnnotation(History.class);
    Class<? extends IBaseResource> type = historyAnnotation.type();
    if (Modifier.isInterface(type.getModifiers())) {
        if (theProvider instanceof IResourceProvider) {
            type = ((IResourceProvider) theProvider).getResourceType();
            if (myIdParamIndex != null) {
                myResourceOperationType = RestOperationTypeEnum.HISTORY_INSTANCE;
            } else {
                myResourceOperationType = RestOperationTypeEnum.HISTORY_TYPE;
            }/*from  ww  w .  j av  a  2 s. c  o  m*/
        } else {
            myResourceOperationType = RestOperationTypeEnum.HISTORY_SYSTEM;
        }
    } else {
        if (myIdParamIndex != null) {
            myResourceOperationType = RestOperationTypeEnum.HISTORY_INSTANCE;
        } else {
            myResourceOperationType = RestOperationTypeEnum.HISTORY_TYPE;
        }
    }

    if (type != IResource.class) {
        myResourceName = theContext.getResourceDefinition(type).getName();
    } else {
        myResourceName = null;
    }

}

From source file:alluxio.shell.AlluxioShellUtilsTest.java

@Test
public void loadCommands() {
    Map<String, ShellCommand> map = new HashMap<>();
    AlluxioShellUtils.loadCommands(mFileSystem, map);

    String pkgName = ShellCommand.class.getPackage().getName();
    Reflections reflections = new Reflections(pkgName);
    Set<Class<? extends ShellCommand>> cmdSet = reflections.getSubTypesOf(ShellCommand.class);
    for (Map.Entry<String, ShellCommand> entry : map.entrySet()) {
        Assert.assertEquals(entry.getValue().getCommandName(), entry.getKey());
        Assert.assertEquals(cmdSet.contains(entry.getValue().getClass()), true);
    }/* w w w .j a v a2  s  . co m*/

    int expectSize = 0;
    for (Class<? extends ShellCommand> cls : cmdSet) {
        if (!Modifier.isAbstract(cls.getModifiers())) {
            expectSize++;
        }
    }
    Assert.assertEquals(expectSize, map.size());
}

From source file:com.googlecode.jsonschema2pojo.integration.EnumIT.java

@Test
@SuppressWarnings("unchecked")
public void enumAtRootCreatesATopLevelType() throws ClassNotFoundException, NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = generateAndCompile("/schema/enum/enumAsRoot.json", "com.example");

    Class<Enum> rootEnumClass = (Class<Enum>) resultsClassLoader.loadClass("com.example.enums.EnumAsRoot");

    assertThat(rootEnumClass.isEnum(), is(true));
    assertThat(isPublic(rootEnumClass.getModifiers()), is(true));

}

From source file:nl.knaw.huygens.timbuctoo.config.TypeRegistry.java

private boolean shouldNotRegister(Class<?> type) {
    return Modifier.isAbstract(type.getModifiers());
}

From source file:objenome.util.ClassUtils.java

/**
 * <p>Returns the desired Method much like {@code Class.getMethod}, however
 * it ensures that the returned Method is from a public class or interface and not
 * from an anonymous inner class. This means that the Method is invokable and
 * doesn't fall foul of Java bug//from   www  . j a  v a 2 s  .c om
 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).</p>
 *
 *  <pre>
 *  <code>Set set = Collections.unmodifiableSet(...);
 *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
 *  Object result = method.invoke(set, new Object[]);</code>
 *  </pre>
 *
 * @param cls  the class to check, not null
 * @param methodName  the name of the method
 * @param parameterTypes  the list of parameters
 * @return the method
 * @throws NullPointerException if the class is null
 * @throws SecurityException if a security violation occurred
 * @throws NoSuchMethodException if the method is not found in the given class
 *  or if the method doesn't conform with the requirements
 */
public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>... parameterTypes)
        throws SecurityException, NoSuchMethodException {

    Method declaredMethod = cls.getMethod(methodName, parameterTypes);
    if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
        return declaredMethod;
    }

    List<Class<?>> candidateClasses = new ArrayList<>(getAllInterfaces(cls));
    candidateClasses.addAll(getAllSuperclasses(cls));

    for (Class<?> candidateClass : candidateClasses) {
        if (!Modifier.isPublic(candidateClass.getModifiers())) {
            continue;
        }
        Method candidateMethod;
        try {
            candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException ex) {
            continue;
        }
        if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
            return candidateMethod;
        }
    }

    throw new NoSuchMethodException(
            "Can't find a public method for " + methodName + ' ' + ArrayUtils.toString(parameterTypes));
}

From source file:org.apache.syncope.core.logic.init.ImplementationClassNamesLoader.java

@Override
public void load() {
    classNames = new EnumMap<>(Type.class);
    for (Type type : Type.values()) {
        classNames.put(type, new HashSet<String>());
    }//from   www .  ja va 2  s  .  co  m

    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(
            false);
    scanner.addIncludeFilter(new AssignableTypeFilter(Reportlet.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(TaskJob.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(SyncActions.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(PushActions.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(SyncCorrelationRule.class));
    // Remove once SYNCOPE-631 is done
    //scanner.addIncludeFilter(new AssignableTypeFilter(PushCorrelationRule.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(PropagationActions.class));
    scanner.addIncludeFilter(new AssignableTypeFilter(Validator.class));

    for (BeanDefinition bd : scanner.findCandidateComponents(StringUtils.EMPTY)) {
        try {
            Class<?> clazz = ClassUtils.resolveClassName(bd.getBeanClassName(),
                    ClassUtils.getDefaultClassLoader());
            boolean isAbsractClazz = Modifier.isAbstract(clazz.getModifiers());

            if (Reportlet.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.REPORTLET).add(clazz.getName());
            }

            if (TaskJob.class.isAssignableFrom(clazz) && !isAbsractClazz
                    && !SyncJob.class.isAssignableFrom(clazz) && !PushJob.class.isAssignableFrom(clazz)) {

                classNames.get(Type.TASKJOB).add(bd.getBeanClassName());
            }

            if (SyncActions.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.SYNC_ACTIONS).add(bd.getBeanClassName());
            }

            if (PushActions.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.PUSH_ACTIONS).add(bd.getBeanClassName());
            }

            if (SyncCorrelationRule.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.SYNC_CORRELATION_RULE).add(bd.getBeanClassName());
            }

            // Uncomment when SYNCOPE-631 is done
            /* if (PushCorrelationRule.class.isAssignableFrom(clazz) && !isAbsractClazz) {
             * classNames.get(Type.PUSH_CORRELATION_RULES).add(metadata.getClassName());
             * } */
            if (PropagationActions.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.PROPAGATION_ACTIONS).add(bd.getBeanClassName());
            }

            if (Validator.class.isAssignableFrom(clazz) && !isAbsractClazz) {
                classNames.get(Type.VALIDATOR).add(bd.getBeanClassName());
            }
        } catch (Throwable t) {
            LOG.warn("Could not inspect class {}", bd.getBeanClassName(), t);
        }
    }
    classNames = Collections.unmodifiableMap(classNames);

    LOG.debug("Implementation classes found: {}", classNames);
}