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:org.apache.hadoop.fs.TestFilterFileSystem.java

@Test
public void testFilterFileSystem() throws Exception {
    for (Method m : FileSystem.class.getDeclaredMethods()) {
        if (Modifier.isStatic(m.getModifiers()))
            continue;
        if (Modifier.isPrivate(m.getModifiers()))
            continue;
        if (Modifier.isFinal(m.getModifiers()))
            continue;

        try {// w w  w .  j a va 2  s  . c om
            DontCheck.class.getMethod(m.getName(), m.getParameterTypes());
            LOG.info("Skipping " + m);
        } catch (NoSuchMethodException exc) {
            LOG.info("Testing " + m);
            try {
                FilterFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
            } catch (NoSuchMethodException exc2) {
                LOG.error("FilterFileSystem doesn't implement " + m);
                throw exc2;
            }
        }
    }
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

/**
 * @param fieldName// ww  w  .j  av a2  s . co m
 *            case insensitive field name
 * @param value
 */
public void fillData(String fieldName, String value) {
    Field[] fields = getFields();// this.getClass().getDeclaredFields();
    for (Field field2 : fields) {
        Field field = field2;
        if (field.getName().equalsIgnoreCase(fieldName)) {
            if (!(Modifier.isFinal(field.getModifiers()))) {
                setField(field, value);
            }
            return;
        }
    }
}

From source file:com.dungnv.vfw5.base.utils.StringUtils.java

public static void escapeHTMLString(Object escapeObject) {
    String oldData = "";
    String newData = "";
    try {/*  www  .jav a  2 s .  co  m*/
        if (escapeObject != null) {
            Class escapeClass = escapeObject.getClass();
            Field fields[] = escapeClass.getDeclaredFields();
            Field superFields[] = escapeClass.getSuperclass().getDeclaredFields();
            Field allField[] = new Field[fields.length + superFields.length];
            System.arraycopy(fields, 0, allField, 0, fields.length);
            System.arraycopy(superFields, 0, allField, fields.length, superFields.length);
            for (Field f : allField) {
                f.setAccessible(true);
                if (f.getType().equals(java.lang.String.class) && !Modifier.isFinal(f.getModifiers())) {
                    if (f.get(escapeObject) != null) {
                        oldData = f.get(escapeObject).toString();
                        newData = StringEscapeUtils.escapeSql(oldData);
                        f.set(escapeObject, newData);
                    }
                } else if (f.getType().isArray()) {
                    if (f.getType().getComponentType().equals(java.lang.String.class)) {
                        String[] tmpArr = (String[]) f.get(escapeObject);
                        if (tmpArr != null) {
                            for (int i = 0; i < tmpArr.length; i++) {
                                tmpArr[i] = StringEscapeUtils.escapeSql(tmpArr[i]);
                            }
                            f.set(escapeObject, tmpArr);
                        }
                    }
                } else if (f.get(escapeObject) instanceof List) {
                    List<Object> tmpList = (List<Object>) f.get(escapeObject);
                    for (int i = 0; i < tmpList.size(); i++) {
                        if (tmpList.get(i) instanceof java.lang.String) {
                            tmpList.set(i, StringEscapeUtils.escapeSql(tmpList.get(i).toString()));
                        }
                    }
                    f.set(escapeObject, tmpList);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ca.sqlpower.object.PersistedSPObjectTest.java

/**
 * All persistable {@link SPObject} implementations must define a static
 * final field which is a list defining the absolute ordering of that
 * class's child type classes. This method ensures that list is retrievable
 * by reflection from the object, that the field is public, static, and
 * final, and that it is nonempty for classes that allow children and empty
 * for classes that do not allow children.
 *//* w  w  w. j av a 2s.c om*/
@SuppressWarnings("unchecked")
public void testAllowedChildTypesField() throws Exception {
    Class<? extends SPObject> classUnderTest = getSPObjectUnderTest().getClass();
    Field childOrderField;
    try {
        childOrderField = classUnderTest.getDeclaredField("allowedChildTypes");
    } catch (NoSuchFieldException ex) {
        fail("Persistent " + classUnderTest + " must have a static final field called allowedChildTypes");
        throw new AssertionError(); // NOTREACHED
    }

    assertEquals("The allowedChildTypes field must be final", true,
            Modifier.isFinal(childOrderField.getModifiers()));

    assertEquals("The allowedChildTypes field must be static", true,
            Modifier.isStatic(childOrderField.getModifiers()));

    // Note: in the future, we will change this to require that the field is private
    assertEquals("The allowedChildTypes field must be public", true,
            Modifier.isPublic(childOrderField.getModifiers()));

    List<Class<? extends SPObject>> allowedChildTypes = (List<Class<? extends SPObject>>) childOrderField
            .get(null);
    if (getSPObjectUnderTest().allowsChildren()) {
        assertFalse(allowedChildTypes.isEmpty());
    } else {
        assertTrue(allowedChildTypes.isEmpty());
    }
}

From source file:org.springframework.aop.framework.Cglib2AopProxy.java

/**
 * Checks for final methods on the <code>Class</code> and writes warnings to the log
 * for each one found./*from  w  w w. j a  v a  2  s.  c om*/
 */
private void doValidateClass(Class proxySuperClass) {
    Method[] methods = proxySuperClass.getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) {
            logger.warn("Unable to proxy method [" + method + "] because it is final: "
                    + "All calls to this method via a proxy will be routed directly to the proxy.");
        }
    }
}

From source file:com.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Instantiates a new <code>FieldInfo</code> object not part of a defined
 * table.//from   www  .j  av a2s.  c om
 *
 * @author vasu
 *
 * @param  cinfo the non-<code>null</code> class info for the POJO
 * @param  field the non-<code>null</code> field to create an info object for
 * @throws IllegalArgumentException if unable to find a getter or setter
 *         method for the field of if improperly annotated
 */
FieldInfoImpl(ClassInfoImpl<T> cinfo, Field field) {
    this.clazz = cinfo.getObjectClass();
    this.cinfo = cinfo;
    this.tinfo = null;
    this.declaringClass = field.getDeclaringClass();
    this.field = field;
    field.setAccessible(true); // make it accessible in case we need to
    this.isFinal = Modifier.isFinal(field.getModifiers());
    this.name = field.getName();
    this.type = DataTypeImpl.unwrapOptionalIfPresent(field.getType(), field.getGenericType());
    this.column = null;
    this.persisted = null;
    this.persister = null;
    this.suffix = field.getAnnotation(SuffixKey.class);
    this.mandatory = true; // keyspace suffixes are mandatory fields
    this.index = null; // we don't care about this for keyspace suffixes
    this.partitionKey = null; // we don't care about this for keyspace suffixes
    this.clusteringKey = null; // we don't care about this for keyspace suffixes
    this.typeKey = null; // we don't care about this for keyspace suffixes
    this.multiKeyType = null; // we don't care about this for keyspace suffixes
    this.definition = null; // we don't care about this for keyspace suffixes
    this.decoder = null; // we don't care about this for keyspace suffixes
    this.getter = findGetterMethod(declaringClass);
    this.setter = findSetterMethod(declaringClass);
    this.finalValue = findFinalValue();
}

From source file:com.nestedbird.modules.formparser.FormParse.java

/**
 * Checks whether the target field is final, meaning it should not be written over...
 * apparently spring writes over final variables
 *
 * @param objectClass - The class of the object we are checking
 * @param fieldName   - The name of the field we are checking
 * @return - Whether or not the field is final
 *//*from  ww  w  .  j  a v a2 s  . c o m*/
private boolean isFieldFinal(final Class objectClass, final String fieldName) {
    final Mutable<Boolean> returnVar = Mutable.of(true);
    getField(objectClass, fieldName)
            .ifPresent(field -> returnVar.mutate(Modifier.isFinal(field.getModifiers())));
    return returnVar.get();
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

/**
 * This will fill random data except those properties which has skip=true in
 * {@link Randomizer} annotation. Use {@link Randomizer} annotation to
 * specify data value to be generated for specific property.
 * /*w ww.  ja va 2 s.  co m*/
 * @see Randomizer
 */
public void fillRandomData() {
    Field[] fields = getFields();
    for (Field field : fields) {
        logger.debug("NAME :: " + field.getName());
        if (!(Modifier.isFinal(field.getModifiers()))) {
            RandomizerTypes type = RandomizerTypes.MIXED;
            int len = 10;
            long min = 0, max = 0;
            String prefix = "", suffix = "";
            String format = "";
            String[] list = {};

            Randomizer randomizer = field.getAnnotation(Randomizer.class);

            if (randomizer != null) {
                if (randomizer.skip()) {
                    continue;
                }
                type = field.getType() == Date.class ? RandomizerTypes.DIGITS_ONLY : randomizer.type();
                len = randomizer.length();
                prefix = randomizer.prefix();
                suffix = randomizer.suffix();
                min = randomizer.minval();
                max = min > randomizer.maxval() ? min : randomizer.maxval();
                format = randomizer.format();
                list = randomizer.dataset();
            } else {
                // @Since 2.1.2 randomizer annotation is must for random
                // value
                // generation
                continue;
            }

            String str = "";
            if ((list == null) || (list.length == 0)) {
                str = StringUtil.isBlank(format)
                        ? RandomStringUtils.random(len, !type.equals(RandomizerTypes.DIGITS_ONLY),
                                !type.equals(RandomizerTypes.LETTERS_ONLY))
                        : StringUtil.getRandomString(format);
            } else {
                str = getRandomValue(list);
            }

            try {
                // deal with IllegalAccessException
                field.setAccessible(true);
                Method setter = null;
                try {
                    setter = this.getClass().getMethod("set" + StringUtil.getTitleCase(field.getName()),
                            String.class);
                } catch (Exception e) {

                }

                if ((field.getType() == String.class) || (null != setter)) {
                    if ((list == null) || (list.length == 0)) {
                        if ((min == max) && (min == 0)) {
                            str = StringUtil.isBlank(format)
                                    ? RandomStringUtils.random(len, !type.equals(RandomizerTypes.DIGITS_ONLY),
                                            !type.equals(RandomizerTypes.LETTERS_ONLY))
                                    : StringUtil.getRandomString(format);

                        } else {
                            str = String.valueOf((int) (Math.random() * ((max - min) + 1)) + min);

                        }
                    }
                    String rStr = prefix + str + suffix;
                    if (null != setter) {
                        setter.setAccessible(true);
                        setter.invoke(this, rStr);
                    } else {
                        field.set(this, rStr);
                    }
                } else {
                    String rStr = "";
                    if ((min == max) && (min == 0)) {
                        rStr = RandomStringUtils.random(len, false, true);
                    } else {
                        rStr = String.valueOf((int) (Math.random() * ((max - min) + 1)) + min);

                    }

                    if (field.getType() == Integer.TYPE) {
                        field.setInt(this, Integer.parseInt(rStr));
                    } else if (field.getType() == Float.TYPE) {
                        field.setFloat(this, Float.parseFloat(rStr));

                    } else if (field.getType() == Double.TYPE) {
                        field.setDouble(this, Double.parseDouble(rStr));

                    } else if (field.getType() == Long.TYPE) {
                        field.setLong(this, Long.parseLong(rStr));

                    } else if (field.getType() == Short.TYPE) {
                        field.setShort(this, Short.parseShort(rStr));
                    } else if (field.getType() == Date.class) {
                        logger.info("filling date " + rStr);
                        int days = Integer.parseInt(rStr);
                        field.set(this, DateUtil.getDate(days));
                    } else if (field.getType() == Boolean.TYPE) {
                        field.setBoolean(this, RandomUtils.nextBoolean());

                    }
                }
            } catch (IllegalArgumentException e) {

                logger.error("Unable to fill random data in field " + field.getName(), e);
            } catch (IllegalAccessException e) {
                logger.error("Unable to Access " + field.getName(), e);
            } catch (InvocationTargetException e) {
                logger.error("Unable to Access setter for " + field.getName(), e);

            }
        }

    }

}

From source file:org.eclipse.buildship.docs.source.SourceMetaDataVisitor.java

private void maybeAddPropertyFromField(GroovySourceAST t) {
    GroovySourceAST parentNode = getParentNode();
    boolean isField = parentNode != null && parentNode.getType() == OBJBLOCK;
    if (!isField) {
        return;//ww  w  . java 2s  .com
    }

    int modifiers = extractModifiers(t);
    boolean isConst = getCurrentClass().isInterface()
            || (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
    if (isConst) {
        visitConst(t);
        return;
    }

    boolean isProp = groovy && !Modifier.isStatic(modifiers) && !Modifier.isPublic(modifiers)
            && !Modifier.isProtected(modifiers) && !Modifier.isPrivate(modifiers);
    if (!isProp) {
        return;
    }

    ASTIterator children = new ASTIterator(t);
    children.skip(MODIFIERS);

    String propertyName = extractIdent(t);
    TypeMetaData propertyType = extractTypeName(children.current);
    ClassMetaData currentClass = getCurrentClass();

    MethodMetaData getterMethod = currentClass
            .addMethod(String.format("get%s", StringUtils.capitalize(propertyName)), propertyType, "");
    PropertyMetaData property = currentClass.addReadableProperty(propertyName, propertyType,
            getJavaDocCommentsBeforeNode(t), getterMethod);
    findAnnotations(t, property);
    if (!Modifier.isFinal(modifiers)) {
        MethodMetaData setterMethod = currentClass
                .addMethod(String.format("set%s", StringUtils.capitalize(propertyName)), TypeMetaData.VOID, "");
        setterMethod.addParameter(propertyName, propertyType);
        currentClass.addWriteableProperty(propertyName, propertyType, getJavaDocCommentsBeforeNode(t),
                setterMethod);
    }
}

From source file:org.pentaho.reporting.engine.classic.core.style.StyleKey.java

public static synchronized void registerClass(final Class c) {
    // Log.debug ("Registering stylekeys from " + c);
    try {// www .  j  av  a2 s .  co  m
        final Field[] fields = c.getFields();
        for (int i = 0; i < fields.length; i++) {
            final Field field = fields[i];
            final int modifiers = field.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                if (Modifier.isFinal(modifiers) == false) {
                    logger.warn("Invalid implementation: StyleKeys should be 'public static final': " + c);
                }
                if (field.getType().isAssignableFrom(StyleKey.class)) {
                    // noinspection UnusedDeclaration
                    final StyleKey value = (StyleKey) field.get(null);
                    // ignore the returned value, all we want is to trigger the key
                    // creation
                    // Log.debug ("Loaded key " + value);
                }
            }
        }
    } catch (IllegalAccessException e) {
        // wont happen, we've checked it..
        logger.warn("Unable to register keys from " + c.getName());
    }
}