Example usage for java.lang.reflect Field isAccessible

List of usage examples for java.lang.reflect Field isAccessible

Introduction

In this page you can find the example usage for java.lang.reflect Field isAccessible.

Prototype

@Deprecated(since = "9")
public boolean isAccessible() 

Source Link

Document

Get the value of the accessible flag for this reflected object.

Usage

From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java

private static Object getFieldValue(Object obj, String fieldName) {
    try {//from   www .  j a  va 2s. co m
        Object iWantThis;

        Field f = obj.getClass().getDeclaredField(fieldName); //NoSuchFieldException
        if (!f.isAccessible()) {
            f.setAccessible(true);
            iWantThis = f.get(obj);
            f.setAccessible(false);
        } else {
            iWantThis = f.get(obj);
        }
        return iWantThis;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 * @param entityClazz//from  www.j ava2 s .com
 * @return the value of the {@link java.reflect.Field} annotated with
 * {@link javax.persistence.Id}.
 */
public static <T, ID extends Serializable> Field findPrimaryKeyField(Class<T> entityClazz) {
    Preconditions.checkNotNull(entityClazz);
    Field f = ReflectionUtils.findField(entityClazz, new AnnotationFieldFilter(Id.class));
    if (f != null && !f.isAccessible()) {
        f.setAccessible(true);
    }
    return f;
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 * @param entityClazz/*  w  w w.ja v a2 s . c om*/
 * @return the value of the {@link java.reflect.Field} annotated with
 * {@link javax.persistence.EmbeddedId}.
 */
public static <T, ID extends Serializable> Field findCompoundKeyField(Class<T> entityClazz) {
    Preconditions.checkNotNull(entityClazz);
    Field f = ReflectionUtils.findField(entityClazz, new AnnotationFieldFilter(EmbeddedId.class));
    if (f != null && !f.isAccessible()) {
        f.setAccessible(true);
    }
    return f;
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateEclipseCsMetaXmlFileRule(String pkg, Class<?> module, Set<Node> children)
        throws Exception {
    final String moduleName = module.getSimpleName();
    final Set<String> properties = getFinalProperties(module);
    final Set<Field> fieldMessages = CheckUtil.getCheckMessages(module);
    final Set<String> messages = new TreeSet<>();

    for (Field fieldMessage : fieldMessages) {
        // below is required for package/private classes
        if (!fieldMessage.isAccessible()) {
            fieldMessage.setAccessible(true);
        }//  w w w.  j  a va  2 s . co  m

        messages.add(fieldMessage.get(null).toString());
    }

    for (Node child : children) {
        final NamedNodeMap attributes = child.getAttributes();

        switch (child.getNodeName()) {
        case "alternative-name":
            final Node internalNameNode = attributes.getNamedItem("internal-name");

            Assert.assertNotNull(
                    pkg + " checkstyle-metadata.xml must contain an internal name for " + moduleName,
                    internalNameNode);

            final String internalName = internalNameNode.getTextContent();

            Assert.assertEquals(
                    pkg + " checkstyle-metadata.xml requires a valid internal-name for " + moduleName,
                    module.getName(), internalName);
            break;
        case "description":
            Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid description for " + moduleName,
                    "%" + moduleName + ".desc", child.getTextContent());
            break;
        case "property-metadata":
            final String propertyName = attributes.getNamedItem("name").getTextContent();

            Assert.assertTrue(pkg + " checkstyle-metadata.xml has an unknown parameter for " + moduleName + ": "
                    + propertyName, properties.remove(propertyName));

            final Node firstChild = child.getFirstChild().getNextSibling();

            Assert.assertNotNull(pkg + " checkstyle-metadata.xml requires atleast one child for " + moduleName
                    + ", " + propertyName, firstChild);
            Assert.assertEquals(pkg + " checkstyle-metadata.xml should have a description for the "
                    + "first child of " + moduleName + ", " + propertyName, "description",
                    firstChild.getNodeName());
            Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid description for " + moduleName
                    + ", " + propertyName, "%" + moduleName + "." + propertyName, firstChild.getTextContent());
            break;
        case "message-key":
            final String key = attributes.getNamedItem("key").getTextContent();

            Assert.assertTrue(
                    pkg + " checkstyle-metadata.xml has an unknown message for " + moduleName + ": " + key,
                    messages.remove(key));
            break;
        default:
            Assert.fail(pkg + " checkstyle-metadata.xml unknown node for " + moduleName + ": "
                    + child.getNodeName());
            break;
        }
    }

    for (String property : properties) {
        Assert.fail(pkg + " checkstyle-metadata.xml missing parameter for " + moduleName + ": " + property);
    }

    for (String message : messages) {
        Assert.fail(pkg + " checkstyle-metadata.xml missing message for " + moduleName + ": " + message);
    }
}

From source file:org.cloudifysource.usm.USMUtils.java

/*************
 * Return's the working directory of a PU.
 *
 * @param ctx//from  w ww  .  j ava 2  s.  co  m
 *            the spring application context.
 * @return the working directory.
 */
public static File getPUWorkDir(final ApplicationContext ctx) {
    File puWorkDir = null;

    if (isRunningInGSC(ctx)) {
        // running in GSC
        final ServiceClassLoader scl = (ServiceClassLoader) ctx.getClassLoader();

        final URL url = scl.getSlashPath();
        URI uri;
        try {
            uri = url.toURI();
        } catch (final URISyntaxException e) {
            throw new IllegalArgumentException("Failed to create URI from URL: " + url, e);
        }

        puWorkDir = new File(uri);

    } else {

        final ResourceApplicationContext rac = (ResourceApplicationContext) ctx;

        try {
            final Field resourcesField = rac.getClass().getDeclaredField("resources");
            final boolean accessibleBefore = resourcesField.isAccessible();

            resourcesField.setAccessible(true);
            final Resource[] resources = (Resource[]) resourcesField.get(rac);
            for (final Resource resource : resources) {
                // find META-INF/spring/pu.xml
                final File file = resource.getFile();
                if (file.getName().equals("pu.xml") && file.getParentFile().getName().equals("spring")
                        && file.getParentFile().getParentFile().getName().equals("META-INF")) {
                    puWorkDir = resource.getFile().getParentFile().getParentFile().getParentFile();
                    break;
                }

            }

            resourcesField.setAccessible(accessibleBefore);
        } catch (final Exception e) {
            throw new IllegalArgumentException("Could not find pu.xml in the ResourceApplicationContext", e);
        }
        if (puWorkDir == null) {
            throw new IllegalArgumentException("Could not find pu.xml in the ResourceApplicationContext");
        }
    }

    if (!puWorkDir.exists()) {
        throw new IllegalStateException("Could not find PU work dir at: " + puWorkDir);
    }

    final File puExtDir = new File(puWorkDir, "ext");
    if (!puExtDir.exists()) {
        throw new IllegalStateException("Could not find PU ext dir at: " + puExtDir);
    }

    return puWorkDir;
}

From source file:meizhi.meizhi.malin.utils.DestroyCleanUtil.java

public static void fixInputMethod(Context context) {
    if (context == null)
        return;/*w  ww .  jav  a  2s  . c  o  m*/
    InputMethodManager inputMethodManager = null;
    try {
        inputMethodManager = (InputMethodManager) context.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
    } catch (Throwable th) {
        th.printStackTrace();
    }
    if (inputMethodManager == null)
        return;
    String[] strArr = new String[] { "mCurRootView", "mServedView", "mNextServedView" };
    for (int i = 0; i < 3; i++) {
        try {
            Field declaredField = inputMethodManager.getClass().getDeclaredField(strArr[i]);
            if (declaredField == null)
                continue;
            if (!declaredField.isAccessible()) {
                declaredField.setAccessible(true);
            }
            Object obj = declaredField.get(inputMethodManager);
            if (obj == null || !(obj instanceof View))
                continue;
            View view = (View) obj;
            if (view.getContext() == context) {
                declaredField.set(inputMethodManager, null);
            } else {
                return;
            }
        } catch (Throwable th) {
            CrashReport.postCatchedException(th);
        }
    }
}

From source file:org.dhatim.util.ClassUtil.java

public static <U> Object getField(Field field, U instance) throws IllegalAccessException {
    boolean isAccessible = field.isAccessible();

    if (!isAccessible) {
        field.setAccessible(true);//from   w w  w . ja  v  a2s  .  co  m
    }

    try {
        return field.get(instance);
    } finally {
        field.setAccessible(isAccessible);
    }
}

From source file:org.rhq.test.arquillian.FakeServerInventory.java

private static Field getPrivateField(Class<?> clazz, String fieldName) throws NoSuchFieldException {
    Field field = clazz.getDeclaredField(fieldName);
    if (!field.isAccessible()) {
        field.setAccessible(true);/*from   w w  w .  j  a v  a2 s .  co m*/
    }

    return field;
}

From source file:org.dhatim.util.ClassUtil.java

public static <U> void setField(Field field, U instance, Object value) throws IllegalAccessException {
    boolean isAccessible = field.isAccessible();

    if (!isAccessible) {
        field.setAccessible(true);//from   ww w  . j  a va2s . c om
    }

    try {
        field.set(instance, value);
    } finally {
        field.setAccessible(isAccessible);
    }
}

From source file:com.unovo.frame.utils.SharedPreferencesHelper.java

private static <T> void buildValuesToMap(Class<?> clx, T t, String preFix, Map<String, Data> map) {
    if (clx == null || clx.equals(Object.class) || t == null) {
        return;/* w  w w . j a v  a 2s.c om*/
    }
    final Field[] fields = clx.getDeclaredFields();
    if (fields == null || fields.length == 0)
        return;

    // Foreach fields
    for (Field field : fields) {
        if (isContSupport(field))
            continue;

        final String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        // Change the Field accessible status
        boolean isAccessible = field.isAccessible();
        if (!isAccessible)
            field.setAccessible(true);

        Object value;
        try {
            value = field.get(t);
        } catch (IllegalArgumentException | IllegalAccessException e) {
            Logger.e(TAG, "buildValuesToMap error:" + e.getMessage());
            continue;
        }

        if (isBasicType(fieldType)) {
            String key = preFix + fieldName;
            if (!map.containsKey(key)) {
                map.put(key, new Data(fieldType, value));
            }
        } else {
            buildValuesToMap(fieldType, value, preFix + fieldName + SEPARATOR, map);
        }
    }

    // Get super class fields
    buildValuesToMap(clx.getSuperclass(), t, preFix, map);
}