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:org.jdto.util.MethodUtils.java

/**
 * <p>Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method. If no such method can
 * be found, return/*w  w  w. ja  va2  s .  co  m*/
 * <code>null</code>.</p>
 *
 * @param method The method that we wish to call
 * @return The accessible method
 */
public static Method getAccessibleMethod(Method method) {

    if (!MemberUtils.isAccessible(method)) {
        return null;
    }
    // If the declaring class is public, we are done
    Class cls = method.getDeclaringClass();
    if (Modifier.isPublic(cls.getModifiers())) {
        return method;
    }
    String methodName = method.getName();
    Class[] parameterTypes = method.getParameterTypes();

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(cls, methodName, parameterTypes);

    // Check the superclass chain
    if (method == null) {
        method = getAccessibleMethodFromSuperclass(cls, methodName, parameterTypes);
    }
    return method;
}

From source file:at.tuwien.ifs.somtoolbox.apps.SOMToolboxMain.java

/**
 * @param screenWidth the with of the screen
 * @param runnables {@link ArrayList} of available runnables.
 *///from w ww .  j  a  va 2 s .  c om
private static void printAvailableRunnables(int screenWidth,
        ArrayList<Class<? extends SOMToolboxApp>> runnables) {
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    ArrayList<Class<? extends SOMToolboxApp>> runnableClassList = new ArrayList<Class<? extends SOMToolboxApp>>();
    ArrayList<String> runnableNamesList = new ArrayList<String>();
    ArrayList<String> runnableDeskrList = new ArrayList<String>();

    for (Class<? extends SOMToolboxApp> c : runnables) {
        try {
            // Ignore abstract classes and interfaces
            if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
                continue;
            }
            runnableClassList.add(c);
            runnableNamesList.add(c.getSimpleName());

            String desk = null;
            try {
                Field f = c.getDeclaredField("DESCRIPTION");
                desk = (String) f.get(null);
            } catch (Exception e) {
            }

            if (desk != null) {
                runnableDeskrList.add(desk);
            } else {
                runnableDeskrList.add("");
            }
        } catch (SecurityException e) {
            // Should not happen - no Security
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    StringBuilder sb = new StringBuilder();
    String lineSep = System.getProperty("line.separator", "\n");

    int maxLen = StringUtils.getLongestStringLength(runnableNamesList);
    sb.append("Runnable classes:").append(lineSep);
    for (int i = 0; i < runnableNamesList.size(); i++) {
        final Type cType = Type.getType(runnableClassList.get(i));
        if (i == 0 || !cType.equals(Type.getType(runnableClassList.get(i - 1)))) {
            sb.append(String.format("-- %s %s%s", cType.toString(),
                    StringUtils.repeatString(screenWidth - (8 + cType.toString().length()), "-"), lineSep));
        }
        sb.append("    ");
        sb.append(runnableNamesList.get(i));
        sb.append(StringUtils.getSpaces(4 + maxLen - runnableNamesList.get(i).length())).append("- ");
        sb.append(runnableDeskrList.get(i));
        sb.append(lineSep);
    }
    System.out.println(StringUtils.wrap(sb.toString(), screenWidth, StringUtils.getSpaces(maxLen + 10), true));
}

From source file:ClassFinder.java

/**
 * /*from   w  w w .  j  a v a  2s.c om*/
 * @param parentClasses
 *            list of classes to check for
 * @param strClassName
 *            name of class to be checked
 * @param contextClassLoader
 *            the classloader to use
 * @return
 */
private static boolean isChildOf(Class[] parentClasses, String strClassName, ClassLoader contextClassLoader) {
    // might throw an exception, assume this is ignorable
    try {
        Class c = Class.forName(strClassName, false, contextClassLoader);

        if (!c.isInterface() && !Modifier.isAbstract(c.getModifiers())) {
            for (Class parentClass : parentClasses) {
                if (parentClass.isAssignableFrom(c)) {
                    return true;
                }
            }
        }
    } catch (Throwable ignored) {

    }
    return false;
}

From source file:controllers.ModuleController.java

private static List<ModuleModel> getNextModules(String input) {
    // get all the supplied view models.
    List<ViewModel> suppliedViewModels = Lists.newArrayList();
    JsonNode inputJson = Json.parse(input);

    // convert json nodes to view models.
    if (inputJson != null && inputJson.isArray()) {
        suppliedViewModels = Lists//from w w  w.j  a  v  a  2  s . c  o m
                .newArrayList(Iterators.transform(inputJson.getElements(), new Function<JsonNode, ViewModel>() {
                    @Override
                    @Nullable
                    public ViewModel apply(@Nullable JsonNode input) {
                        if (!input.isTextual()) {
                            return null;
                        }
                        return createViewModelQuietly(
                                fetchResource(UuidUtils.create(input.asText()), PersistentObject.class), null);

                    }
                }));
    } else if (inputJson != null && inputJson.isObject()) {
        suppliedViewModels.add(createViewModelQuietly(inputJson, null));
    }

    suppliedViewModels = Lists.newArrayList(Iterables.filter(suppliedViewModels, Predicates.notNull()));

    // get all the modules that can use these inputs.
    Map<Module, Double> nullModulesMap = Maps.newHashMap();
    Map<Module, Double> modulesMap = Maps.newHashMap();
    Reflections reflections = new Reflections("controllers.modules", Play.application().classloader());
    for (Class<? extends Module> moduleClass : reflections.getSubTypesOf(Module.class)) {
        // we're not interested in abstract classes.
        if (Modifier.isAbstract(moduleClass.getModifiers())) {
            continue;
        }

        // get the Module.Requires/Requireses annotation for each module class.
        // the requirements within each Module.Require are ANDed.
        // the requirements across multiple Module.Require annotations are ORed.
        List<Module.Requires> requireds = Lists.newArrayList();
        if (moduleClass.isAnnotationPresent(Module.Requires.class)) {
            requireds.add(moduleClass.getAnnotation(Module.Requires.class));
        }
        if (moduleClass.isAnnotationPresent(Module.Requireses.class)) {
            Collections.addAll(requireds, moduleClass.getAnnotation(Module.Requireses.class).value());
        }

        if (requireds.size() == 0) {
            requireds.add(null);
        }

        for (Module.Requires required : requireds) {
            final Set<Class<? extends ViewModel>> requiredViewModelClasses = Sets.newHashSet();
            if (required != null) {
                Collections.addAll(requiredViewModelClasses, required.value());
            }

            // get all the supplied view modules that are relevant to this module.
            List<ViewModel> usefulViewModels = Lists
                    .newArrayList(Iterables.filter(suppliedViewModels, new Predicate<ViewModel>() {
                        @Override
                        public boolean apply(@Nullable ViewModel input) {
                            // if this class is required, then return true.
                            if (requiredViewModelClasses.contains(input.getClass())) {
                                return true;
                            }

                            // if any of its super classes are required, that also works.
                            for (Class<?> superClass : ClassUtils.getAllSuperclasses(input.getClass())) {
                                if (requiredViewModelClasses.contains(superClass)) {
                                    return true;
                                }
                            }

                            return false;
                        }
                    }));

            // if all the requirements were satisfied.
            if (usefulViewModels.size() >= requiredViewModelClasses.size()) {
                // try to create an instance of the module.
                Module module = null;
                try {
                    module = moduleClass.newInstance();
                    module.setViewModels(usefulViewModels);
                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
                    module = null;
                } finally {
                    // if no module was created, just ignore.
                    if (module == null) {
                        continue;
                    }
                }

                // let's not divide by zero!
                double relevancyScore = suppliedViewModels.size() != 0
                        ? usefulViewModels.size() / (double) suppliedViewModels.size()
                        : 1.0;

                // keep null modules separate.
                Map<Module, Double> targetModulesMap = null;
                if (requiredViewModelClasses.size() > 0) {
                    // if a module of this type does not exist, add it.
                    if (Maps.filterKeys(modulesMap, Predicates.instanceOf(moduleClass)).size() == 0) {
                        targetModulesMap = modulesMap;
                    }
                } else {
                    targetModulesMap = nullModulesMap;
                }
                if (targetModulesMap != null) {
                    targetModulesMap.put(module, relevancyScore);
                }
            }
        }
    }

    // use null modules only if there are no regular ones.
    if (modulesMap.size() == 0) {
        modulesMap = nullModulesMap;
    }

    // convert to view models.
    Set<ModuleModel> moduleViewModels = Sets.newHashSet(
            Iterables.transform(modulesMap.entrySet(), new Function<Entry<Module, Double>, ModuleModel>() {
                @Override
                @Nullable
                public ModuleModel apply(@Nullable Entry<Module, Double> input) {
                    return new ModuleModel(input.getKey()).setRelevancyScore(input.getValue());
                }
            }));

    // order first by relevance and then by name.
    return Ordering.from(new Comparator<ModuleModel>() {
        @Override
        public int compare(ModuleModel o1, ModuleModel o2) {
            int relDiff = (int) Math.round((o2.relevancyScore - o1.relevancyScore) * 1000);
            if (relDiff == 0) {
                return o1.name.compareTo(o2.name);
            }

            return relDiff;
        }
    }).sortedCopy(moduleViewModels);
}

From source file:sx.blah.discord.modules.ModuleLoader.java

/**
 * Manually adds a module class to be considered for loading.
 *
 * @param clazz The module class.//w w w.  ja  v a2  s.co  m
 */
public static void addModuleClass(Class<? extends IModule> clazz) {
    if (!Modifier.isAbstract(clazz.getModifiers()) && !Modifier.isInterface(clazz.getModifiers())
            && !modules.contains(clazz)) {
        modules.add(clazz);
    }
}

From source file:org.seedstack.seed.core.utils.BaseClassSpecifications.java

/**
 * Checks if the class is abstract./* ww w  . jav a 2  s  .com*/
 *
 * @return the specification
 */
public static Specification<Class<?>> classIsAbstract() {
    return new AbstractSpecification<Class<?>>() {
        @Override
        public boolean isSatisfiedBy(Class<?> candidate) {

            return candidate != null && Modifier.isAbstract(candidate.getModifiers());
        }
    };
}

From source file:org.zilverline.util.ClassFinder.java

/**
 * Convenience method to get a list of classes that can be instantiated.
 * /*  www  .  j  a v  a  2  s .com*/
 * @param superclass an interface or base class
 * @return Array of discovered classes
 * @throws IOException
 * @throws ClassNotFoundException
 */
public static Class[] getInstantiableSubclasses(Class superclass) throws IOException, ClassNotFoundException {
    ArrayList instantiableSubclasses = new ArrayList();
    List classes = findClassesThatExtend(superclass);
    for (Iterator iter = classes.iterator(); iter.hasNext();) {
        String className = (String) iter.next();
        try {
            log.debug("Trying to instantiate: " + className);
            Class clazz = Class.forName(className);
            int modifiers = clazz.getModifiers();
            if (!Modifier.isAbstract(modifiers)) {
                log.debug("Can instantiate: " + className);
                instantiableSubclasses.add(clazz);
            }
        } catch (Throwable t) {
            log.warn("Can't instantiate: " + className, t);
        }
    }
    return (Class[]) instantiableSubclasses.toArray(new Class[0]);
}

From source file:org.jdto.util.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// w  w  w  .  j a v  a2s  .  com
 * <code>null</code>.</p>
 *
 * @param cls Class to be checked
 * @param methodName Method name of the method we wish to call
 * @param parameterTypes The parameter type signatures
 * @return the accessible method or
 * <code>null</code> if not found
 */
private static Method getAccessibleMethodFromSuperclass(Class cls, String methodName, Class[] parameterTypes) {
    Class parentClass = cls.getSuperclass();
    while (parentClass != null) {
        if (Modifier.isPublic(parentClass.getModifiers())) {
            try {
                return parentClass.getMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                return null;
            }
        }
        parentClass = parentClass.getSuperclass();
    }
    return null;
}

From source file:com.hurence.logisland.documentation.DocGenerator.java

/**
 * Generates documentation into the work/docs dir specified from a specified set of class
 *///from w  w w .  j ava2 s . c  o m
public static void generate(final File docsDirectory, final String writerType) {

    Map<String, Class> extensionClasses = new TreeMap<>();

    PluginLoader.getRegistry().forEach((className, classLoader) -> {
        try {
            extensionClasses.put(className, classLoader.loadClass(className));
        } catch (Exception e) {
            logger.error("Unable to load class " + className, e);

        }
    });

    ClassFinder.findClasses(clazz -> {
        if (!clazz.startsWith("BOOT-INF") && clazz.contains("logisland") && !clazz.contains("Mock")
                && !clazz.contains("shade")) {
            try {
                Class c = Class.forName(clazz);
                if (c.isAssignableFrom(ConfigurableComponent.class) && !Modifier.isAbstract(c.getModifiers())) {
                    extensionClasses.put(c.getSimpleName(), c);
                }
            } catch (Throwable e) {
                logger.error("Unable to load class " + clazz + " : " + e.getMessage());
            }
        }

        return true; // return false if you don't want to see any more classes
    });

    docsDirectory.mkdirs();

    // write headers for single rst file
    if (writerType.equals("rst"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        if (baseDocumenationFile.exists())
            baseDocumenationFile.delete();

        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("Components");
            writer.println("==========");
            writer.println(
                    "You'll find here the list of all usable Processors, Engines, Services and other components "
                            + "that can be usable out of the box in your analytics streams");
            writer.println();
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    } else if (writerType.equals("json"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        if (baseDocumenationFile.exists())
            baseDocumenationFile.delete();

        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("[");
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    }

    Class[] sortedExtensionsClasses = new Class[extensionClasses.size()];
    extensionClasses.values().

            toArray(sortedExtensionsClasses);

    Arrays.sort(sortedExtensionsClasses, new Comparator<Class>()

    {
        @Override
        public int compare(Class s1, Class s2) {
            // the +1 is to avoid including the '.' in the extension and to avoid exceptions
            // EDIT:
            // We first need to make sure that either both files or neither file
            // has an extension (otherwise we'll end up comparing the extension of one
            // to the start of the other, or else throwing an exception)
            final int s1Dot = s1.getName().lastIndexOf('.');
            final int s2Dot = s2.getName().lastIndexOf('.');
            if ((s1Dot == -1) == (s2Dot == -1)) { // both or neither
                String s1Name = s1.getName().substring(s1Dot + 1);
                String s2Name = s2.getName().substring(s2Dot + 1);
                return s1Name.compareTo(s2Name);
            } else if (s1Dot == -1) { // only s2 has an extension, so s1 goes first
                return -1;
            } else { // only s1 has an extension, so s1 goes second
                return 1;
            }
        }
    });

    logger.info("Generating " + writerType + " documentation for " + Arrays.stream(sortedExtensionsClasses).

            count() + " components in: " + docsDirectory);

    Arrays.stream(sortedExtensionsClasses).

            forEach(extensionClass ->

    {
                final Class componentClass = extensionClass.asSubclass(ConfigurableComponent.class);
                try {
                    document(docsDirectory, componentClass, writerType);

                } catch (Exception e) {
                    logger.error("Unexpected error for " + extensionClass, e);
                }

            });

    if (writerType.equals("json"))

    {
        final File baseDocumenationFile = new File(docsDirectory, OUTPUT_FILE + "." + writerType);
        try (final PrintWriter writer = new PrintWriter(new FileOutputStream(baseDocumenationFile, true))) {
            writer.println("]");
        } catch (FileNotFoundException e) {
            logger.warn(e.getMessage());
        }
    }

}

From source file:org.hibernate.internal.util.ReflectHelper.java

/**
 * Determine if the given class is declared abstract.
 *
 * @param clazz The class to check./* ww w  .  j a  v a2  s .co m*/
 * @return True if the class is abstract, false otherwise.
 */
public static boolean isAbstractClass(Class clazz) {
    int modifier = clazz.getModifiers();
    return Modifier.isAbstract(modifier) || Modifier.isInterface(modifier);
}