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:com.izforge.izpack.util.SelfModifier.java

/**
 * Check the method for the required properties (public, static, params:(String[])).
 *
 * @param method the method//w  ww. jav  a 2  s  .co  m
 * @throws NullPointerException     if <code>method</code> is null
 * @throws IllegalArgumentException if <code>method</code> is not public, static, and take a
 *                                  String array as it's only argument, or of it's declaring class is not public.
 * @throws SecurityException        if access to the method is denied
 */
private void initMethod(Method method) {
    int mod = method.getModifiers();
    if ((mod & Modifier.PUBLIC) == 0 || (mod & Modifier.STATIC) == 0) {
        throw new IllegalArgumentException("Method not public and static");
    }

    Class[] params = method.getParameterTypes();
    if (params.length != 1 || !params[0].isArray()
            || !"java.lang.String".equals(params[0].getComponentType().getName())) {
        throw new IllegalArgumentException("Method must accept String array");
    }

    Class clazz = method.getDeclaringClass();
    mod = clazz.getModifiers();
    if ((mod & Modifier.PUBLIC) == 0 || (mod & Modifier.INTERFACE) != 0) {
        throw new IllegalArgumentException("Method must be in a public class");
    }

    this.method = method;
}

From source file:org.gridgain.grid.util.json.GridJsonDeserializer.java

/**
 * Retrieves {@link JSONArray} class for deserialization.
 *
 * @param arr Array for which retrieve class.
 * @param dfltCls Default class./*from  w  w w  .j a  va2s.c  o  m*/
 * @return Class of the passed array.
 * @throws GridException Thrown if any error occurs while deserialization.
 */
private static Class getArrayClass(JSONArray arr, @Nullable Class dfltCls) throws GridException {
    assert arr != null;

    Class cls = null;

    if (arr.size() > 0) {
        boolean isFound = false;

        for (Object elem : arr)
            if (elem instanceof JSONObject) {
                JSONObject obj = (JSONObject) elem;

                if (obj.containsKey(AT_CLASS))
                    if (!isFound) {
                        cls = loadClass(obj, AT_CLASS);

                        isFound = true;
                    } else
                        throw new GridException("JSON array can contain only one element with attribute "
                                + AT_CLASS + ": " + arr);
            }
    }

    if (cls == null)
        if (dfltCls != null)
            cls = dfltCls;
        else
            cls = getDefaultClass(arr);

    assert cls != null;

    if ((cls.isInterface() || Modifier.isAbstract(cls.getModifiers())) && Iterable.class.isAssignableFrom(cls))
        if (Set.class.isAssignableFrom(cls))
            cls = HashSet.class;
        else if (Queue.class.isAssignableFrom(cls))
            cls = LinkedList.class;
        else
            cls = ArrayList.class;

    return cls;
}

From source file:au.com.addstar.cellblock.configuration.AutoConfig.java

private <T> Set<T> newSet(Class<? extends Set<T>> setClass, Collection<T> data)
        throws InvalidConfigurationException {
    Validate.isTrue(!Modifier.isAbstract(setClass.getModifiers()),
            "You cannot use an abstract type for AutoConfiguration");

    Constructor<? extends Set<T>> constructor;

    try {/*from ww w  .  j a v a  2 s  .  co  m*/
        constructor = setClass.getConstructor(Collection.class);

        return constructor.newInstance(data);
    } catch (Exception e) {
        throw new InvalidConfigurationException(e);
    }
}

From source file:au.com.addstar.cellblock.configuration.AutoConfig.java

private <T> List<T> newList(Class<? extends List<T>> listClass, Collection<T> data)
        throws InvalidConfigurationException {
    Validate.isTrue(!Modifier.isAbstract(listClass.getModifiers()),
            "You cannot use an abstract type for AutoConfiguration");

    Constructor<? extends List<T>> constructor;

    try {//from   ww w . jav  a  2  s.  c om
        constructor = listClass.getConstructor(Collection.class);

        return constructor.newInstance(data);
    } catch (Exception e) {
        throw new InvalidConfigurationException(e);
    }
}

From source file:org.evosuite.testcase.statements.FunctionalMockStatement.java

public static boolean canBeFunctionalMocked(Type type) {

    Class<?> rawClass = new GenericClass(type).getRawClass();
    final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

    if (Properties.hasTargetClassBeenLoaded() && (rawClass.equals(targetClass))) {
        return false;
    }/*from  w  w  w.ja  va  2s .  c  o  m*/

    if (EvoSuiteMock.class.isAssignableFrom(rawClass) || MockList.isAMockClass(rawClass.getName())
            || rawClass.equals(Class.class) || rawClass.isArray() || rawClass.isPrimitive()
            || rawClass.isAnonymousClass() || rawClass.isEnum() ||
            //note: Mockito can handle package-level classes, but we get all kinds of weird exceptions with instrumentation :(
            !Modifier.isPublic(rawClass.getModifiers())) {
        return false;
    }

    if (!InstrumentedClass.class.isAssignableFrom(rawClass) && Modifier.isFinal(rawClass.getModifiers())) {
        /*
        if a class has not been instrumented (eg because belonging to javax.*),
        then if it is final we cannot mock it :(
        recall that instrumentation does remove the final modifiers
         */
        return false;
    }

    //FIXME: tmp fix to avoid mocking any class with package access methods
    try {
        for (Method m : rawClass.getDeclaredMethods()) {

            /*
            Unfortunately, it does not seem there is a "isPackageLevel" method, so we have
            to go by exclusion
             */

            if (!Modifier.isPublic(m.getModifiers()) && !Modifier.isProtected(m.getModifiers())
                    && !Modifier.isPrivate(m.getModifiers()) && !m.isBridge() && !m.isSynthetic()
                    && !m.getName().equals(ClassResetter.STATIC_RESET)) {
                return false;
            }
        }
    } catch (NoClassDefFoundError | Exception e) {
        //this could happen if we failed to load the class
        AtMostOnceLogger.warn(logger,
                "Failed to check if can mock class " + rawClass.getName() + ": " + e.getMessage());
        return false;
    }

    //avoid cases of infinite recursions
    boolean onlySelfReturns = true;
    for (Method m : rawClass.getDeclaredMethods()) {
        if (!rawClass.equals(m.getReturnType())) {
            onlySelfReturns = false;
            break;
        }
    }

    if (onlySelfReturns && rawClass.getDeclaredMethods().length > 0) {
        //avoid weird cases like java.lang.Appendable
        return false;
    }

    //ad-hoc list of classes we should not really mock
    List<Class<?>> avoid = Arrays.asList(
    //add here if needed
    );

    if (avoid.contains(rawClass)) {
        return false;
    }

    return true;
}

From source file:org.apache.geode.internal.DeployedJar.java

/**
 * Check to see if the class implements the Function interface. If so, it will be registered with
 * FunctionService. Also, if the functions's class was originally declared in a cache.xml file
 * then any properties specified at that time will be reused when re-registering the function.
 *
 * @param clazz Class to check for implementation of the Function class
 * @return A collection of Objects that implement the Function interface.
 *///w  w w . j ava 2 s .  c  o  m
private Collection<Function> getRegisterableFunctionsFromClass(Class<?> clazz) {
    final List<Function> registerableFunctions = new ArrayList<>();

    try {
        if (Function.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
            boolean registerUninitializedFunction = true;
            if (Declarable.class.isAssignableFrom(clazz)) {
                try {
                    final List<Properties> propertiesList = ((InternalCache) CacheFactory.getAnyInstance())
                            .getDeclarableProperties(clazz.getName());

                    if (!propertiesList.isEmpty()) {
                        registerUninitializedFunction = false;
                        // It's possible that the same function was declared multiple times in cache.xml
                        // with different properties. So, register the function using each set of
                        // properties.
                        for (Properties properties : propertiesList) {
                            @SuppressWarnings("unchecked")
                            Function function = newFunction((Class<Function>) clazz, true);
                            if (function != null) {
                                ((Declarable) function).init(properties);
                                if (function.getId() != null) {
                                    registerableFunctions.add(function);
                                }
                            }
                        }
                    }
                } catch (CacheClosedException ignored) {
                    // That's okay, it just means there were no properties to init the function with
                }
            }

            if (registerUninitializedFunction) {
                @SuppressWarnings("unchecked")
                Function function = newFunction((Class<Function>) clazz, false);
                if (function != null && function.getId() != null) {
                    registerableFunctions.add(function);
                }
            }
        }
    } catch (Exception ex) {
        logger.error("Attempting to register function from JAR file: {}", this.file.getAbsolutePath(), ex);
    }

    return registerableFunctions;
}

From source file:pt.webdetails.cda.settings.SettingsManager.java

public DataAccessConnectionDescriptor[] getDataAccessDescriptors(boolean refreshCache) {

    ArrayList<DataAccessConnectionDescriptor> descriptors = new ArrayList<DataAccessConnectionDescriptor>();
    // First we need a list of all the data accesses. We're getting that from a .properties file, as a comma-separated array.

    Properties components = CdaEngine.getEnvironment().getCdaComponents();
    String[] dataAccesses = StringUtils.split(StringUtils.defaultString(components.getProperty("dataAccesses")),
            ",");

    // We apply some sanity checks to the dataAccesses listed:
    //    1. It can't be abstract,
    //    2. It must inherit from AbstractDataAccess
    // For any class that passes those tests, we get its getDataAccessDescripts() method, and use it to get a description.
    for (String dataAccess : dataAccesses) {

        Class<?> clazz = null;
        String className = DATA_ACCESS_PACKAGE + '.' + dataAccess;
        try {/* w ww  .  j a  va  2 s  .co  m*/
            clazz = Class.forName(className);
        } catch (Exception e) {
            logger.error(MessageFormat.format("Couldn\'t load class {0}!", className));
            continue;
        }

        if (Modifier.isAbstract(clazz.getModifiers())) {
            logger.debug(dataAccess + " is abstract: Skipping");
        } else if (AbstractDataAccess.class.isAssignableFrom(clazz)) {
            try {
                @SuppressWarnings("unchecked")
                DataAccessConnectionDescriptor[] descriptor = DataAccessConnectionDescriptor
                        .fromClass((Class<? extends AbstractDataAccess>) clazz);
                descriptors.addAll(Arrays.asList(descriptor));
            } catch (InvocationTargetException e) {
                Throwable cause = e.getTargetException();
                if (cause.getClass() == UnsupportedOperationException.class) {
                    logger.warn("DataAccess " + dataAccess + " doesn't support discoverability!");
                } else {
                    logger.error("DataAccess " + dataAccess + " did something wrong!");
                }
            } catch (Exception e) {
                logger.error("DataAccess " + dataAccess + " did something wrong!");
            }
        }

    }
    return descriptors.toArray(new DataAccessConnectionDescriptor[descriptors.size()]);
}

From source file:org.dd4t.databind.builder.json.JsonModelConverter.java

private <T extends BaseViewModel> BaseViewModel buildModelForField(final JsonNode currentField,
        final Class<T> modelClassToUse) throws SerializationException {

    if (Modifier.isAbstract(modelClassToUse.getModifiers())
            || Modifier.isInterface(modelClassToUse.getModifiers())) {

        // Get root element name
        final String rootElementName = getRootElementNameFromComponentOrEmbeddedField(currentField);
        if (StringUtils.isNotEmpty(rootElementName)) {
            // attempt get a concrete class for this interface

            final Class<? extends BaseViewModel> concreteClass = databinder
                    .getConcreteModel(modelClassToUse.getCanonicalName(), rootElementName);
            if (concreteClass == null) {
                LOG.error("Attempt to find a concrete model class for interface or abstract class: {} failed "
                        + "miserably as there was no registered class for root element name: '{}' Will return null"
                        + ".", modelClassToUse.getCanonicalName(), rootElementName);
                return null;
            }/*from www  .  ja  va  2  s  . c o  m*/
            LOG.debug("Building: {}", concreteClass.getCanonicalName());
            return getBaseViewModel(currentField, concreteClass);
        } else {
            LOG.error(
                    "Attempt to find a concrete model class for interface or abstract class: {} failed "
                            + "miserably as a root element name could not be found. Will return null.",
                    modelClassToUse.getCanonicalName());
            return null;
        }

    } else {

        return getBaseViewModel(currentField, modelClassToUse);
    }
}

From source file:edu.isi.karma.rdf.OfflineRdfGenerator.java

private KR2RMLRDFWriter createBloomFilterWriter(PrintWriter bloomfilterpw, Boolean isRDF, String baseURI)
        throws Exception {

    Reflections reflections = new Reflections("edu.isi.karma.kr2rml.writer");

    Set<Class<? extends KR2RMLRDFWriter>> subTypes = reflections.getSubTypesOf(KR2RMLRDFWriter.class);

    for (Class<? extends KR2RMLRDFWriter> subType : subTypes) {
        if (!Modifier.isAbstract(subType.getModifiers()) && !subType.isInterface()
                && subType.getName().equals("BloomFilterKR2RMLRDFWriter"))
            try {
                KR2RMLRDFWriter writer = subType.newInstance();
                writer.setWriter(bloomfilterpw);
                Properties p = new Properties();
                p.setProperty("is.rdf", isRDF.toString());
                p.setProperty("base.uri", baseURI);
                writer.initialize(p);/*from w  w w .j ava2 s. c  o m*/
                return writer;
            } catch (Exception e) {
                bloomfilterpw.close();
                throw new Exception("Unable to instantiate bloom filter writer", e);
            }
    }

    bloomfilterpw.close();
    throw new Exception("Bloom filter writing support not enabled.  Please recompile with -Pbloom");
}

From source file:lineage2.gameserver.scripts.Scripts.java

/**
 * Method load.//from ww  w. j  a v  a  2s  . co m
 */
private void load() {
    _log.info("Scripts: Loading...");

    List<Class<?>> classes = new ArrayList<>();

    boolean result = false;

    File f = new File("../libs/lineage2-scripts.jar");
    if (f.exists()) {
        JarInputStream stream = null;
        try {
            stream = new JarInputStream(new FileInputStream(f));
            JarEntry entry = null;
            while ((entry = stream.getNextJarEntry()) != null) {
                if (entry.getName().contains(ClassUtils.INNER_CLASS_SEPARATOR)
                        || !entry.getName().endsWith(".class")) {
                    continue;
                }

                String name = entry.getName().replace(".class", "").replace("/", ".");

                Class<?> clazz = Class.forName(name);
                if (Modifier.isAbstract(clazz.getModifiers())) {
                    continue;
                }
                classes.add(clazz);
            }
            result = true;
        } catch (Exception e) {
            _log.error("Fail to load scripts.jar!", e);
            classes.clear();
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    if (!result) {
        result = load(classes, "");
    }

    if (!result) {
        _log.error("Scripts: Failed loading scripts!");
        Runtime.getRuntime().exit(0);
        return;
    }

    _log.info("Scripts: Loaded " + classes.size() + " classes.");

    Class<?> clazz;
    for (int i = 0; i < classes.size(); i++) {
        clazz = classes.get(i);
        _classes.put(clazz.getName(), clazz);
    }
}