Example usage for java.lang.reflect Modifier isFinal

List of usage examples for java.lang.reflect Modifier isFinal

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isFinal.

Prototype

public static boolean isFinal(int mod) 

Source Link

Document

Return true if the integer argument includes the final modifier, false otherwise.

Usage

From source file:edu.wright.daselab.linkgen.ConfigurationParams.java

public final static boolean checkStatusOnLoad() throws Exception {
    // using reflection to check all properties/params fields.
    // you can use annotation for better retrieval
    // http://stackoverflow.com/questions/2020202/pitfalls-in-getting-member-variable-values-in-java-with-reflection
    // by this time, none of the values are empty.
    String name = "";
    String value = "";
    logger.info("Displaying all param values:");
    boolean isFine = true;
    Field[] fields = ConfigurationParams.class.getDeclaredFields();
    for (Field field : fields) {
        // check only final static fields
        if (!Modifier.isFinal((field.getModifiers())) || (!Modifier.isStatic(field.getModifiers()))) {
            continue;
        }//  www. j  av  a2s . c  om
        name = field.getName();
        try {
            value = (String) field.get(null).toString();
        } catch (Exception e) {
            Monitor.error(Error.INVALID_CONFIG_PARAMS.toString());
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
        }
        if ((value == null) || value.toString().trim().equals("")) {
            isFine = false;
        }
        String status = isFine ? "OK" : "Failed";
        logger.info(status + " \t" + name + "=" + value);
        if (!isFine)
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
    }
    return isFine;
}

From source file:com.sxj.mybatis.orm.builder.GenericStatementBuilder.java

public GenericStatementBuilder(Configuration configuration, final Class<?> entityClass) {
    super(configuration);
    this.entityClass = entityClass;
    sharded = ConfigurationProperties.isSharded(configuration);
    String resource = entityClass.getName().replace('.', '/') + ".java (best guess)";
    assistant = new MapperBuilderAssistant(configuration, resource);
    entity = entityClass.getAnnotation(Entity.class);
    mapperType = entity.mapper();//from w  ww  . ja  v  a  2s .  c  o m

    if (!mapperType.isAssignableFrom(Void.class)) {
        namespace = mapperType.getName();
    } else {
        namespace = entityClass.getName();
    }
    assistant.setCurrentNamespace(namespace);
    Collection<String> cacheNames = configuration.getCacheNames();
    for (String name : cacheNames)
        if (namespace.equals(name)) {
            assistant.useCacheRef(name);
            break;
        }

    databaseId = super.getConfiguration().getDatabaseId();
    lang = super.getConfiguration().getDefaultScriptingLanuageInstance();

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Table table = entityClass.getAnnotation(Table.class);
    if (table == null) {
        tableName = CaseFormatUtils.camelToUnderScore(entityClass.getSimpleName());
    } else {
        tableName = table.name();
    }

    ///~~~~~~~~~~~~~~~~~~~~~~
    idField = AnnotationUtils.findDeclaredFieldWithAnnoation(Id.class, entityClass);
    if (!sharded && (this.idField.isAnnotationPresent(GeneratedValue.class))
            && (((GeneratedValue) this.idField.getAnnotation(GeneratedValue.class))
                    .strategy() == GenerationType.UUID))
        columnFields.add(idField);
    else
        columnFields.add(idField);
    versionField = AnnotationUtils.findDeclaredFieldWithAnnoation(Version.class, entityClass);

    ReflectionUtils.doWithFields(entityClass, new FieldCallback() {

        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
            if (field.isAnnotationPresent(Column.class))
                columnFields.add(field);
            if (field.isAnnotationPresent(Sn.class))
                containSn = true;

        }
    }, new FieldFilter() {

        public boolean matches(Field field) {
            if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
                return false;
            }

            for (Annotation annotation : field.getAnnotations()) {
                if (Transient.class.isAssignableFrom(annotation.getClass())
                        || Id.class.isAssignableFrom(annotation.getClass())) {
                    return false;
                }
            }

            return true;
        }
    });
}

From source file:org.unitils.mock.core.MockFactory.java

public Mock<?> createChainedMock(MatchingInvocation matchingInvocation) {
    Object matchingProxy = matchingInvocation.getProxy();
    Map<Method, Mock<?>> chainedMocksForProxy = chainedMocks.get(matchingProxy);
    if (chainedMocksForProxy == null) {
        chainedMocksForProxy = new HashMap<Method, Mock<?>>();
        chainedMocks.put(matchingProxy, chainedMocksForProxy);
    }/*from   www  .j  a v a2  s  .c o m*/
    Method method = matchingInvocation.getMethod();
    Mock<?> chainedMock = chainedMocksForProxy.get(method);
    if (chainedMock != null) {
        return chainedMock;
    }
    String name = matchingInvocation.getInnerMockName();
    Class<?> mockedType = matchingInvocation.getReturnType();
    if (mockedType == Void.TYPE) {
        return null;
    }
    if (mockedType.isPrimitive() || mockedType.isArray() || Modifier.isFinal(mockedType.getModifiers())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to create chained mock " + name + " for return type +" + mockedType
                    + ". Chaining not supported for primitive, arrays or final types, returning null.");
        }
        return null;
    }
    try {
        chainedMock = createMockObject(name, mockedType, true);
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to create chained mock " + name + " for return type +" + mockedType
                    + ". Chaining not supported, returning null.");
        }
        return null;
    }
    chainedMocksForProxy.put(method, chainedMock);
    return chainedMock;
}

From source file:adalid.core.Instance.java

private void finaliseFields() {
    String name;//  w  w  w  .  j a  va 2  s . com
    Class<?> type;
    int modifiers;
    boolean restricted;
    Object o;
    int depth = depth();
    int round = round();
    for (Field field : XS1.getFields(getClass(), Instance.class)) { // getClass().getDeclaredFields()
        field.setAccessible(true);
        logger.trace(field);
        name = field.getName();
        type = field.getType();
        if (!InstanceField.class.isAssignableFrom(type)) {
            continue;
        }
        modifiers = field.getModifiers();
        restricted = Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers);
        if (restricted) {
            continue;
        }
        String errmsg = "failed to initialize field \"" + field + "\" at " + this;
        try {
            o = field.get(this);
            if (o == null) {
                logger.debug(message(type, name, o, depth, round));
            } else if (o instanceof InstanceField) {
                finaliseInstanceField(field, (InstanceField) o);
            }
        } catch (IllegalArgumentException | IllegalAccessException ex) {
            logger.error(errmsg, ThrowableUtils.getCause(ex));
            TLC.getProject().getParser().increaseErrorCount();
        }
    }
}

From source file:com.cognifide.slice.mapper.GenericSlingMapper.java

/**
 * Returns true if a field can be assigned, i.e. is not final, nor static
 * /*from  w  w  w  .j a  v  a 2 s.c  om*/
 * @param field the field being investigated
 * @return true if the field is assignable, false otherwise
 */
private boolean isFieldAssignable(Field field) {
    int modifiers = field.getModifiers();
    if (Modifier.isFinal(modifiers)) {
        return false;
    } // else

    if (Modifier.isStatic(modifiers)) {
        return false;
    } // else
    return true;
}

From source file:de.codesourcery.eve.skills.util.XMLMapper.java

private BeanDescription createBeanDescription(Class<?> clasz) {

    BeanDescription result = new BeanDescription();
    for (java.lang.reflect.Field f : clasz.getDeclaredFields()) {
        final int modifiers = f.getModifiers();
        if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers)) {
            continue;
        }//  w  w w. j a v a  2  s  .  co m
        if (!f.isAccessible()) {
            f.setAccessible(true);
        }
        result.addField(f);
    }
    return result;
}

From source file:RevEngAPI.java

/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
    className = c.getName();/*w w  w.j  a v a 2s  . c  om*/
    // pre-compute offset for stripping package name
    classNameOffset = className.lastIndexOf('.') + 1;

    // Inner class
    if (className.indexOf('$') != -1)
        return;

    // get name, as String, with . changed to /
    String slashName = className.replace('.', '/');
    String fileName = slashName + ".java";

    System.out.println(className + " --> " + fileName);

    String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
    new File(dirName).mkdirs();

    // create the file.
    PrintWriter out = new PrintWriter(new FileWriter(fileName));

    out.println("// Generated by RevEngAPI for class " + className);

    // If in a package, say so.
    Package pkg;
    if ((pkg = c.getPackage()) != null) {
        out.println("package " + pkg.getName() + ';');
        out.println();
    }
    // print class header
    int cMods = c.getModifiers();
    printMods(cMods, out);
    out.print("class ");
    out.print(trim(c.getName()));
    out.print(' ');
    // XXX get superclass 
    out.println('{');

    // print constructors
    Constructor[] ctors = c.getDeclaredConstructors();
    for (int i = 0; i < ctors.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Constructors");
        }
        Constructor cons = ctors[i];
        int mods = cons.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(cons.getName()) + "(");
        Class[] classes = cons.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.print("\t}");
    }

    // print method names
    Method[] mems = c.getDeclaredMethods();
    for (int i = 0; i < mems.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Methods");
        }
        Method m = mems[i];
        if (m.getName().startsWith("access$"))
            continue;
        int mods = m.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(m.getReturnType());
        out.print(' ');
        out.print(trim(m.getName()) + "(");
        Class[] classes = m.getParameterTypes();
        for (int j = 0; j < classes.length; j++) {
            if (j > 0)
                out.print(", ");
            out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j));
        }
        out.println(") {");
        out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
        out.println("\t}");
    }

    // print fields
    Field[] flds = c.getDeclaredFields();
    for (int i = 0; i < flds.length; i++) {
        if (i == 0) {
            out.println();
            out.println("\t// Fields");
        }
        Field f = flds[i];
        int mods = f.getModifiers();
        if (Modifier.isPrivate(mods))
            continue;
        out.print('\t');
        printMods(mods, out);
        out.print(trim(f.getType().getName()));
        out.print(' ');
        out.print(f.getName());
        if (Modifier.isFinal(mods)) {
            try {
                out.print(" = " + f.get(null));
            } catch (IllegalAccessException ex) {
                out.print("; // " + ex.toString());
            }
        }
        out.println(';');
    }
    out.println("}");
    //out.flush();
    out.close();
}

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   ww w. j  a  v  a2s  .  c om

    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.lmn.fc.common.utilities.pending.Utilities.java

/***********************************************************************************************
 * Show the Member Modifiers.//from  www  .  j av a2  s. c  o m
 *
 * @param member
 *
 * @return String
 */

public static String showModifiers(final Member member) {
    final int modifiers;
    final StringBuffer buffer;

    buffer = new StringBuffer();

    if (member != null) {
        modifiers = member.getModifiers();

        if (Modifier.isAbstract(modifiers)) {
            buffer.append("Abstract ");
        }

        if (Modifier.isFinal(modifiers)) {
            buffer.append("Final ");
        }

        if (Modifier.isInterface(modifiers)) {
            buffer.append("Interface ");
        }

        if (Modifier.isNative(modifiers)) {
            buffer.append("Native ");
        }

        if (Modifier.isPrivate(modifiers)) {
            buffer.append("Private ");
        }

        if (Modifier.isProtected(modifiers)) {
            buffer.append("Protected ");
        }

        if (Modifier.isPublic(modifiers)) {
            buffer.append("Public ");
        }

        if (Modifier.isStatic(modifiers)) {
            buffer.append("Static ");
        }

        if (Modifier.isStrict(modifiers)) {
            buffer.append("Strict ");
        }

        if (Modifier.isSynchronized(modifiers)) {
            buffer.append("Synchronized ");
        }

        if (Modifier.isTransient(modifiers)) {
            buffer.append("Transient ");
        }

        if (Modifier.isVolatile(modifiers)) {
            buffer.append("Volatile ");
        }
    }

    return (buffer.toString().trim());
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static boolean isFinal(Method method) {
    return Modifier.isFinal(method.getModifiers());
}