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.bstek.dorado.idesupport.initializer.FloatControlRuleTemplateInitializer.java

public void initRuleTemplate(RuleTemplate ruleTemplate, InitializerContext initializerContext)
        throws Exception {
    String typeName = ruleTemplate.getType();
    if (StringUtils.isNotEmpty(typeName)) {
        Class<?> type = ClassUtils.forName(typeName);
        if (type.equals(FloatControl.class) || Modifier.isAbstract(type.getModifiers())) {
            return;
        }/* w w w .j a v a2s . com*/

        boolean found = false;
        for (Class<?> _interface : type.getInterfaces()) {
            if (_interface.equals(FloatControl.class)) {
                found = true;
                break;
            }
        }
        if (!found) {
            return;
        }
    }

    RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager();
    RuleTemplate floatControlRule = ruleTemplateManager.getRuleTemplate("FloatControl");
    if (floatControlRule == null) {
        floatControlRule = new AutoRuleTemplate("FloatControl", FloatControl.class.getName());
        floatControlRule.setAbstract(true);
        ruleTemplateManager.addRuleTemplate(floatControlRule);
    }

    RuleTemplate[] parents = ruleTemplate.getParents();
    if (parents != null) {
        RuleTemplate[] oldParents = parents;
        parents = new RuleTemplate[oldParents.length + 1];
        System.arraycopy(oldParents, 0, parents, 0, oldParents.length);
        parents[oldParents.length] = floatControlRule;
    } else {
        parents = new RuleTemplate[] { floatControlRule };
    }
    ruleTemplate.setParents(parents);
}

From source file:org.apache.asterix.om.typecomputer.ExceptionTest.java

@Test
public void test() throws Exception {
    // Tests all usual type computers.
    Reflections reflections = new Reflections("org.apache.asterix.om.typecomputer", new SubTypesScanner(false));
    Set<Class<? extends IResultTypeComputer>> classes = reflections.getSubTypesOf(IResultTypeComputer.class);
    int numTypeComputers = 0;
    for (Class<? extends IResultTypeComputer> c : classes) {
        if (Modifier.isAbstract(c.getModifiers())) {
            continue;
        }/*from  w w w  .ja v a 2s. c o  m*/
        testTypeComputer(c);
        ++numTypeComputers;
    }
    // Currently, there are 78 type computers.
    Assert.assertTrue(numTypeComputers >= 78);
}

From source file:blue.lapis.pore.impl.event.PoreEventTest.java

@Test
public void findUnimplementedEvents() throws IOException {
    Set<Class<?>> events = Sets.newLinkedHashSet();

    for (ClassPath.ClassInfo info : PoreTests.getClassPath().getTopLevelClassesRecursive(BUKKIT_PACKAGE)) {
        try {/*w  w w.  j  av  a  2 s  .c  o m*/
            Class<?> event = info.load();
            if (Event.class.isAssignableFrom(event) && !Modifier.isAbstract(event.getModifiers())) {
                events.add(event);
            }
        } catch (Throwable e) {
            PoreTests.getLogger().warn("Failed to load {}", info, e);
        }
    }

    for (ClassPath.ClassInfo info : PoreTests.getClassPath().getTopLevelClassesRecursive(PORE_PACKAGE)) {
        Class<?> type;
        try {
            type = info.load();
            if (!Event.class.isAssignableFrom(type)) {
                continue;
            }
        } catch (Throwable e) {
            PoreTests.getLogger().warn("Failed to load {}", info, e);
            continue;
        }

        events.remove(type.getSuperclass());
    }

    if (!events.isEmpty()) {
        for (Class<?> event : events) {
            String bukkitPackage = StringUtils.removeStart(event.getPackage().getName(), BUKKIT_PACKAGE + '.');
            PoreTests.getLogger().warn("{}: Pore{} is missing", bukkitPackage, event.getSimpleName());
        }
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.domain.delta.DeltaNodeTypeTest.java

public void testThereIsOneDeltaNodeTypePerDeltaClass() throws Exception {
    List<String> errors = new ArrayList<String>();
    for (Class<? extends Delta> deltaClass : domainReflections.getSubTypesOf(Delta.class)) {
        if (Modifier.isAbstract(deltaClass.getModifiers()) || deltaClass.isAnonymousClass())
            continue;
        try {//  w  ww .j  a v  a  2 s  .  co  m
            DeltaNodeType.valueForDeltaClass(deltaClass);
        } catch (IllegalArgumentException iae) {
            errors.add(iae.getMessage());
        }
    }

    if (!errors.isEmpty()) {
        fail("* " + StringUtils.join(errors.iterator(), "\n* "));
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.domain.delta.DeltaNodeTypeTest.java

public void testThereIsOneDeltaNodeTypePerChangeableClass() throws Exception {
    List<String> errors = new ArrayList<String>();
    for (Class<? extends Changeable> cClass : domainReflections.getSubTypesOf(Changeable.class)) {
        if (Modifier.isAbstract(cClass.getModifiers()) || cClass.isAnonymousClass())
            continue;
        try {//w  w w .jav a 2 s .  co  m
            DeltaNodeType.valueForNodeClass(cClass);
        } catch (IllegalArgumentException iae) {
            errors.add(iae.getMessage());
        }
    }

    if (!errors.isEmpty()) {
        fail("* " + StringUtils.join(errors.iterator(), "\n* "));
    }
}

From source file:org.bitpipeline.lib.friendlyjson.JSONEntity.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object fromJson(Class<?> clazz, Object json) throws JSONMappingException {
    if (json == null)
        return null;
    Object fromJson = null;/* ww  w.j ava2 s.c o  m*/
    if (clazz == null) {
        try {
            fromJson = JSONEntity.fromJson(json);
        } catch (JSONException e) {
            e.printStackTrace();
            throw new JSONMappingException(e);
        }
    } else {
        Constructor<?> constructor;
        ;
        if (JSONEntity.class.isAssignableFrom(clazz)) { // A JSON Entity.
            Class<?> enclosingClass = clazz.getEnclosingClass();
            if (enclosingClass != null && (clazz.getModifiers() & Modifier.STATIC) == 0) { // it's a non static inner class
                try {
                    constructor = clazz.getDeclaredConstructor(enclosingClass, JSONObject.class);
                } catch (Exception e) {
                    throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e);
                }

                try {
                    /* we actually don't know the enclosing object...
                     * this will be a problem with inner classes that
                     * reference the enclosing class instance at 
                     * constructor time... although with json entities
                     * that should not happen. */
                    fromJson = constructor.newInstance(null, json);
                } catch (Exception e) {
                    throw new JSONMappingException(e);
                }
            } else { // static inner class
                try {
                    constructor = clazz.getDeclaredConstructor(JSONObject.class);
                } catch (Exception e) {
                    throw new JSONMappingException(clazz.getName() + JSONEntity.MSG_MUST_HAVE_CONSTRUCTOR, e);
                }

                try {
                    fromJson = constructor.newInstance(json);
                } catch (Exception e) {
                    throw new JSONMappingException("clazz = " + clazz.getName() + "; json = " + json.toString(),
                            e);
                }
            }
        } else if (clazz.isEnum()) {
            try {
                fromJson = Enum.valueOf((Class<Enum>) clazz, json.toString());
            } catch (Exception e) {
                fromJson = null;
            }
        } else {
            try {
                fromJson = JSONEntity.fromJson(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    if (clazz != null && !clazz.isAssignableFrom(fromJson.getClass()))
        throw new JSONMappingException("Was expeting a " + clazz.getName() + " but received a "
                + fromJson.getClass().getName() + " instead.");
    return fromJson;
}

From source file:org.apache.ambari.server.utils.TestShellCommandUtil.java

public void testResultsClassIsPublic() throws Exception {
    Class resultClass = ShellCommandUtil.Result.class;

    assertEquals(Modifier.PUBLIC, resultClass.getModifiers() & Modifier.PUBLIC);

    for (Method method : resultClass.getMethods()) {
        assertEquals(method.getName(), Modifier.PUBLIC, (method.getModifiers() & Modifier.PUBLIC));
    }/*from w w w .  j a va  2 s . c o  m*/
}

From source file:edu.northwestern.bioinformatics.studycalendar.xml.writers.DeltaXmlSerializerFactoryTest.java

@SuppressWarnings({ "RawUseOfParameterizedType" })
public void testASerializerCanBeBuiltForEveryDelta() throws Exception {
    List<String> errors = new ArrayList<String>();
    for (Class<? extends Delta> aClass : domainReflections.getSubTypesOf(Delta.class)) {
        if (!Modifier.isAbstract(aClass.getModifiers()) && !aClass.isAnonymousClass()) {
            Delta d = aClass.newInstance();
            try {
                factory.createXmlSerializer(d);
            } catch (StudyCalendarError sce) {
                errors.add(String.format("Failure with %s: %s", d, sce.getMessage()));
            }/*from  ww w.j  a v a  2s .  c  o  m*/
        }
    }
    if (!errors.isEmpty()) {
        fail(StringUtils.join(errors.iterator(), '\n'));
    }
}

From source file:therian.module.SelfContainedTherianModule.java

@SuppressWarnings("rawtypes")
private <O extends Operator> O newInstance(Class<O> c) {
    if (c.isInterface()) {
        return null;
    }//from  w  ww  . j  a va 2  s .  c  om
    if (Modifier.isAbstract(c.getModifiers())) {
        return null;
    }
    final Class<?>[] paramTypes;
    final Object[] args;
    if (Modifier.isStatic(c.getModifiers())) {
        paramTypes = ArrayUtils.EMPTY_CLASS_ARRAY;
        args = ArrayUtils.EMPTY_OBJECT_ARRAY;
    } else {
        paramTypes = new Class[] { getClass() };
        args = new Object[] { this };
    }
    final Constructor<O> cs = ConstructorUtils.getMatchingAccessibleConstructor(c, paramTypes);
    if (cs == null) {
        return null;
    }
    try {
        return cs.newInstance(args);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.twinsoft.convertigo.beans.CheckBeans.java

private static void analyzeJavaClass(String javaClassName) {
    try {/* w  w w . j a va  2 s .  c  om*/
        Class<?> javaClass = Class.forName(javaClassName);
        String javaClassSimpleName = javaClass.getSimpleName();

        if (!DatabaseObject.class.isAssignableFrom(javaClass)) {
            //Error.NON_DATABASE_OBJECT.add(javaClassName);
            return;
        }

        nBeanClass++;

        String dboBeanInfoClassName = javaClassName + "BeanInfo";
        MySimpleBeanInfo dboBeanInfo = null;
        try {
            dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance();
        } catch (ClassNotFoundException e) {
            if (!Modifier.isAbstract(javaClass.getModifiers())) {
                Error.MISSING_BEAN_INFO
                        .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")");
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor();

        // Check abstract class
        if (Modifier.isAbstract(javaClass.getModifiers())) {
            // Check icon (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check icon (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            if (declaredIconName != null) {
                Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName);
            }

            // Check display name
            if (!beanDescriptor.getDisplayName().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (!beanDescriptor.getShortDescription().equals("?")) {
                Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName);
            }
        } else {
            nBeanClassNotAbstract++;

            // Check bean declaration in database_objects.xml
            if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) {
                Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName);
            }

            // Check icon name policy (16x16)
            String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo,
                    MySimpleBeanInfo.ICON_COLOR_16x16);
            String expectedIconName = javaClassName.replace(javaClassSimpleName,
                    "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (16x16)
            File iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check icon name policy (32x32)
            declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32);
            expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName);
            expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32";
            expectedIconName = expectedIconName.toLowerCase() + ".png";
            if (declaredIconName != null) {
                if (!declaredIconName.equals(expectedIconName)) {
                    Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + "      Declared: "
                            + declaredIconName + "\n" + "      Expected: " + expectedIconName);
                }
            }

            // Check icon file (32x32)
            iconFile = new File(srcBase + declaredIconName);
            if (!iconFile.exists()) {
                Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName);
            } else {
                icons.remove(declaredIconName);
            }

            // Check display name
            if (beanDescriptor.getDisplayName().equals("?")) {
                Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName);
            }

            // Check description
            if (beanDescriptor.getShortDescription().equals("?")) {
                Error.BEAN_MISSING_DESCRIPTION.add(javaClassName);
            }
        }

        // Check declared bean properties
        PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            String propertyName = propertyDescriptor.getName();
            try {
                javaClass.getDeclaredField(propertyName);
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                try {
                    // Try to find it in the upper classes
                    javaClass.getField(propertyName);
                } catch (SecurityException e1) {
                    // printStackTrace();
                } catch (NoSuchFieldException e1) {
                    Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName);
                }
            }
        }

        Method[] methods = javaClass.getDeclaredMethods();
        List<Method> listMethods = Arrays.asList(methods);
        List<String> listMethodNames = new ArrayList<String>();
        for (Method method : listMethods) {
            listMethodNames.add(method.getName());
        }

        Field[] fields = javaClass.getDeclaredFields();

        for (Field field : fields) {
            int fieldModifiers = field.getModifiers();

            // Ignore static fields (constants)
            if (Modifier.isStatic(fieldModifiers))
                continue;

            String fieldName = field.getName();

            String errorMessage = javaClassName + ": " + field.getName();

            // Check bean info
            PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo);
            if (propertyDescriptor != null) {
                // Check bean property name policy
                if (!propertyDescriptor.getName().equals(fieldName)) {
                    Error.PROPERTY_NAMING_POLICY.add(errorMessage);
                }

                String declaredGetter = propertyDescriptor.getReadMethod().getName();
                String declaredSetter = propertyDescriptor.getWriteMethod().getName();

                String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
                String expectedGetter = "get" + formattedFieldName;
                String expectedSetter = "set" + formattedFieldName;

                // Check getter name policy
                if (!declaredGetter.equals(expectedGetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared getter: " + declaredGetter + "\n"
                                    + "      Expected getter: " + expectedGetter);
                }

                // Check setter name policy
                if (!declaredSetter.equals(expectedSetter)) {
                    Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH
                            .add(errorMessage + "\n" + "      Declared setter: " + declaredSetter + "\n"
                                    + "      Expected setter: " + expectedSetter);
                }

                // Check required private modifiers for bean property
                if (!Modifier.isPrivate(fieldModifiers)) {
                    Error.PROPERTY_NOT_PRIVATE.add(errorMessage);
                }

                // Check getter
                if (!listMethodNames.contains(declaredGetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared getter not found: " + declaredGetter);
                }

                // Check setter
                if (!listMethodNames.contains(declaredSetter)) {
                    Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND
                            .add(errorMessage + " - Declared setter not found: " + declaredGetter);
                }

                // Check non transient modifier
                if (Modifier.isTransient(fieldModifiers)) {
                    Error.PROPERTY_TRANSIENT.add(errorMessage);
                }
            } else if (!Modifier.isTransient(fieldModifiers)) {
                Error.FIELD_NOT_TRANSIENT.add(errorMessage);
            }
        }
    } catch (ClassNotFoundException e) {
        System.out.println("ERROR on " + javaClassName);
        e.printStackTrace();
    }
}