Example usage for java.lang.reflect Modifier FINAL

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

Introduction

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

Prototype

int FINAL

To view the source code for java.lang.reflect Modifier FINAL.

Click Source Link

Document

The int value representing the final modifier.

Usage

From source file:hu.bme.mit.sette.common.model.snippet.SnippetContainer.java

/**
 * Validates the fields of the class./*w  ww .  ja  va  2  s.  co m*/
 *
 * @param validator
 *            a validator
 */
private void validateFields(final AbstractValidator<?> validator) {
    // check: only constant ("public static final") or synthetic fields
    for (Field field : javaClass.getDeclaredFields()) {
        if (field.isSynthetic()) {
            // skip for synthetic fields (e.g. switch for enum generates
            // synthetic methods and fields)
            continue;
        }

        FieldValidator v = new FieldValidator(field);
        v.withModifiers(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL);
        v.withoutModifiers(Modifier.SYNCHRONIZED | Modifier.TRANSIENT | Modifier.VOLATILE);

        validator.addChildIfInvalid(v);
    }
}

From source file:hu.bme.mit.sette.common.model.snippet.SnippetInputFactoryContainer.java

/**
 * Validates methods of the class.//from  w w  w . jav a 2  s.com
 *
 * @param validator
 *            a validator
 * @return a map containing the input factory methods by their name
 */
private Map<String, Method> validateMethods(final AbstractValidator<?> validator) {
    // check: only "public static" or synthetic methods
    Map<String, Method> factoryMethods = new HashMap<String, Method>();

    for (Method method : javaClass.getDeclaredMethods()) {
        if (method.isSynthetic()) {
            // skip synthetic methods
            continue;
        }

        MethodValidator v = new MethodValidator(method);

        if (factoryMethods.get(method.getName()) != null) {
            v.addException("The method must have a unique name");
        }

        v.withModifiers(Modifier.PUBLIC | Modifier.STATIC);
        v.withoutModifiers(Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE | Modifier.SYNCHRONIZED);

        factoryMethods.put(method.getName(), method);

        validator.addChildIfInvalid(v);
    }

    return factoryMethods;
}

From source file:org.apache.hadoop.hbase.fs.HFileSystem.java

/**
 * Add an interceptor on the calls to the namenode#getBlockLocations from the DFSClient
 * linked to this FileSystem. See HBASE-6435 for the background.
 * <p/>/*  w ww.  j  a v a2  s.c  o  m*/
 * There should be no reason, except testing, to create a specific ReorderBlocks.
 *
 * @return true if the interceptor was added, false otherwise.
 */
static boolean addLocationsOrderInterceptor(Configuration conf, final ReorderBlocks lrb) {
    if (!conf.getBoolean("hbase.filesystem.reorder.blocks", true)) { // activated by default
        LOG.debug("addLocationsOrderInterceptor configured to false");
        return false;
    }

    FileSystem fs;
    try {
        fs = FileSystem.get(conf);
    } catch (IOException e) {
        LOG.warn("Can't get the file system from the conf.", e);
        return false;
    }

    if (!(fs instanceof DistributedFileSystem)) {
        LOG.debug("The file system is not a DistributedFileSystem. " + "Skipping on block location reordering");
        return false;
    }

    DistributedFileSystem dfs = (DistributedFileSystem) fs;
    DFSClient dfsc = dfs.getClient();
    if (dfsc == null) {
        LOG.warn("The DistributedFileSystem does not contain a DFSClient. Can't add the location "
                + "block reordering interceptor. Continuing, but this is unexpected.");
        return false;
    }

    try {
        Field nf = DFSClient.class.getDeclaredField("namenode");
        nf.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(nf, nf.getModifiers() & ~Modifier.FINAL);

        ClientProtocol namenode = (ClientProtocol) nf.get(dfsc);
        if (namenode == null) {
            LOG.warn("The DFSClient is not linked to a namenode. Can't add the location block"
                    + " reordering interceptor. Continuing, but this is unexpected.");
            return false;
        }

        ClientProtocol cp1 = createReorderingProxy(namenode, lrb, conf);
        nf.set(dfsc, cp1);
        LOG.info("Added intercepting call to namenode#getBlockLocations so can do block reordering"
                + " using class " + lrb.getClass());
    } catch (NoSuchFieldException e) {
        LOG.warn("Can't modify the DFSClient#namenode field to add the location reorder.", e);
        return false;
    } catch (IllegalAccessException e) {
        LOG.warn("Can't modify the DFSClient#namenode field to add the location reorder.", e);
        return false;
    }

    return true;
}

From source file:edu.illinois.ncsa.springdata.SpringData.java

/**
 * Check each field in object to see if it is already seen. This will modify
 * collections, lists and arrays as well as the fields in an object.
 * //  ww  w.  ja  v  a 2s.c  o  m
 * @param obj
 *            the object to be checked for duplicates.
 * @param seen
 *            objects that have already been checked.
 * @return the object with all duplicates removed
 */
private static <T> T removeDuplicate(T obj, Map<String, Object> seen) {
    if (obj == null) {
        return null;
    }
    if (obj instanceof AbstractBean) {
        String id = ((AbstractBean) obj).getId();
        if (seen.containsKey(id)) {
            return (T) seen.get(id);
        }
        seen.put(id, obj);

        // check all subfields
        for (Field field : obj.getClass().getDeclaredFields()) {
            if ((field.getModifiers() & Modifier.FINAL) == 0) {
                try {
                    field.setAccessible(true);
                    field.set(obj, removeDuplicate(field.get(obj), seen));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    } else if (obj instanceof Collection<?>) {
        Collection col = (Collection) obj;
        ArrayList arr = new ArrayList(col);
        col.clear();
        for (int i = 0; i < arr.size(); i++) {
            Object x = removeDuplicate(arr.get(i), seen);
            col.add(x);
        }
    } else if (obj instanceof Map<?, ?>) {
        Map map = (Map) obj;
        ArrayList<Entry> arr = new ArrayList(map.entrySet());
        map.clear();
        for (int i = 0; i < arr.size(); i++) {
            Object k = removeDuplicate(arr.get(i).getKey(), seen);
            Object v = removeDuplicate(arr.get(i).getValue(), seen);
            map.put(k, v);
        }
    } else if (obj.getClass().isArray()) {
        Object[] arr = (Object[]) obj;
        for (int i = 0; i < arr.length; i++) {
            arr[i] = removeDuplicate(arr[i], seen);
        }
    }

    return obj;
}

From source file:org.jboss.pnc.causeway.ctl.ImportControllerTest.java

static void setFinalField(Object obj, Field field, Object newValue) throws ReflectiveOperationException {
    field.setAccessible(true);/*  ww w . j ava 2  s  .  c  o  m*/

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(obj, newValue);
}

From source file:org.apache.hadoop.net.TestDNS.java

/**
 * Change DNS#cachedHostName to something which cannot be a real
 * host name. Uses reflection since it is a 'private final' field.
 *///from   ww w.ja v a2s  . c  om
private String changeDnsCachedHostname(final String newHostname) throws Exception {
    final String oldCachedHostname = DNS.getDefaultHost(DEFAULT);
    Field field = DNS.class.getDeclaredField("cachedHostname");
    field.setAccessible(true);
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.set(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newHostname);
    return oldCachedHostname;
}

From source file:net.minecraftforge.common.util.EnumHelper.java

public static void setFailsafeFieldValue(Field field, @Nullable Object target, @Nullable Object value)
        throws Exception {
    field.setAccessible(true);//from  ww  w  . j  av  a 2s.  c  o  m
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    Object fieldAccessor = newFieldAccessor.invoke(reflectionFactory, field, false);
    fieldAccessorSet.invoke(fieldAccessor, target, value);
}

From source file:com.viadee.acceptancetests.roo.addon.AcceptanceTestGroupMetadata.java

private static DefaultMethodMetadata newAcceptanceTestGroupMethod(String identifier, JavaType returnType,
        String methodName, List<AnnotatedJavaType> parameters, List<JavaSymbolName> parameterNames,
        String body) {/*ww  w  .  j  av a  2s .c  o m*/
    return new DefaultMethodMetadata(identifier, Modifier.FINAL, new JavaSymbolName(methodName), returnType,
            parameters, parameterNames, null, null, body);
}

From source file:hd3gtv.mydmam.db.orm.CassandraOrm.java

private ArrayList<Field> getOrmobjectUsableFields() {
    ArrayList<Field> result = new ArrayList<Field>();

    Field[] fields = this.reference.getFields();
    Field field;/*from  ww  w  .  j  av  a2 s  .  c  o  m*/
    int mod;
    for (int pos_df = 0; pos_df < fields.length; pos_df++) {
        field = fields[pos_df];
        if (field.isAnnotationPresent(Transient.class)) {
            /**
             * Is transient ?
             */
            continue;
        }
        if (field.getName().equals("key")) {
            /**
             * Not this (primary key)
             */
            continue;
        }
        mod = field.getModifiers();

        if ((mod & Modifier.PROTECTED) != 0)
            continue;
        if ((mod & Modifier.PRIVATE) != 0)
            continue;
        if ((mod & Modifier.ABSTRACT) != 0)
            continue;
        if ((mod & Modifier.STATIC) != 0)
            continue;
        if ((mod & Modifier.FINAL) != 0)
            continue;
        if ((mod & Modifier.TRANSIENT) != 0)
            continue;
        if ((mod & Modifier.INTERFACE) != 0)
            continue;

        try {
            result.add(field);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    return result;
}

From source file:com.github.mbenson.privileged.weaver.PrivilegedMethodWeaver.java

private CtClass createAction(CtClass type, CtMethod impl, Class<?> iface)
        throws NotFoundException, CannotCompileException, IOException {
    final boolean exc = impl.getExceptionTypes().length > 0;

    final CtClass actionType = classPool.get(iface.getName());

    final String simpleName = generateActionClassname(impl);
    debug("Creating action type %s for method %s", simpleName, toString(impl));
    final CtClass result = type.makeNestedClass(simpleName, true);
    result.addInterface(actionType);//from  w  w w .  j  a  va 2s .  c  o  m

    final CtField owner;
    if (Modifier.isStatic(impl.getModifiers())) {
        owner = null;
    } else {
        owner = new CtField(type, generateName("owner"), result);
        owner.setModifiers(Modifier.PRIVATE | Modifier.FINAL);
        debug("Adding owner field %s to %s", owner.getName(), simpleName);
        result.addField(owner);
    }

    final List<String> propagatedParameters = new ArrayList<String>();
    int index = -1;
    for (final CtClass param : impl.getParameterTypes()) {
        final String f = String.format("arg%s", Integer.valueOf(++index));
        final CtField fld = new CtField(param, f, result);
        fld.setModifiers(Modifier.PRIVATE | Modifier.FINAL);
        debug("Copying parameter %s from %s to %s.%s", index, toString(impl), simpleName, f);
        result.addField(fld);
        propagatedParameters.add(f);
    }
    {
        final StrBuilder constructor = new StrBuilder(simpleName).append('(');
        boolean sep = false;
        final Body body = new Body();

        for (final CtField fld : result.getDeclaredFields()) {
            if (sep) {
                constructor.append(", ");
            } else {
                sep = true;
            }
            constructor.append(fld.getType().getName()).append(' ').append(fld.getName());
            body.appendLine("this.%1$s = %1$s;", fld.getName());
        }
        constructor.append(") ").append(body.complete());

        final String c = constructor.toString();
        debug("Creating action constructor:");
        debug(c);
        result.addConstructor(CtNewConstructor.make(c, result));
    }
    {
        final StrBuilder run = new StrBuilder("public Object run() ");
        if (exc) {
            run.append("throws Exception ");
        }
        final Body body = new Body();
        final CtClass rt = impl.getReturnType();
        final boolean isVoid = rt.equals(CtClass.voidType);
        if (!isVoid) {
            body.append("return ");
        }
        final String deref = Modifier.isStatic(impl.getModifiers()) ? type.getName() : owner.getName();
        final String call = String.format("%s.%s(%s)", deref, impl.getName(),
                StringUtils.join(propagatedParameters, ", "));

        if (!isVoid && rt.isPrimitive()) {
            body.appendLine("%2$s.valueOf(%1$s);", call, ((CtPrimitiveType) rt).getWrapperName());
        } else {
            body.append(call).append(';').appendNewLine();

            if (isVoid) {
                body.appendLine("return null;");
            }
        }

        run.append(body.complete());

        final String r = run.toString();
        debug("Creating run method:");
        debug(r);
        result.addMethod(CtNewMethod.make(r, result));
    }
    getClassFileWriter().write(result);
    debug("Returning action type %s", result);
    return result;
}