Example usage for java.lang.reflect Method isAccessible

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

Introduction

In this page you can find the example usage for java.lang.reflect Method 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:Main.java

/**
 * check for getter method and return the value.{@link #getGetter(Object, String)}.
 *///from   w ww  .  j  ava2 s .c o  m
public static Object getProperty(Object bean, String property) {
    if (bean == null || TextUtils.isEmpty(property)) {
        return null;
    }
    try {
        Method getter = getGetter(bean, property);
        if (getter != null) {
            if (!getter.isAccessible()) {
                getter.setAccessible(true);
            }
            return getter.invoke(bean, new Object[0]);
        }
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:Main.java

/**
 * Called internally by installGtkPopupBugWorkaround. Returns a specific
 * GTK style object.//from  w  w  w  .  ja v a 2s .  c om
 * 
 * @param styleFactory
 *            The GTK style factory.
 * @param component
 *            The target component of the style.
 * @param regionName
 *            The name of the target region of the style.
 * @return The GTK style.
 * @throws Exception
 *             When reflection fails.
 */
private static Object getGtkStyle(Object styleFactory, JComponent component, String regionName)
        throws Exception {
    // Create the region object
    Class<?> regionClass = Class.forName("javax.swing.plaf.synth.Region");
    Field field = regionClass.getField(regionName);
    Object region = field.get(regionClass);

    // Get and return the style
    Class<?> styleFactoryClass = styleFactory.getClass();
    Method method = styleFactoryClass.getMethod("getStyle", new Class<?>[] { JComponent.class, regionClass });
    boolean accessible = method.isAccessible();
    method.setAccessible(true);
    Object style = method.invoke(styleFactory, component, region);
    method.setAccessible(accessible);
    return style;
}

From source file:com.example.administrator.mytestdemo.premission.yzjpermission.AndPermission.java

static <T extends Annotation> void callback(Object o, Class<T> clazz, int requestCode) {
    Method[] methods = PermissionUtils.findMethodForRequestCode(o.getClass(), clazz, requestCode);
    try {/*  w  ww.  ja v  a 2s .  com*/
        for (Method method : methods) {
            if (!method.isAccessible())
                method.setAccessible(true);
            method.invoke(o, null);
        }
    } catch (Exception e) {
        Log.e("AndPermission", "Callback methods fail.");
    }
}

From source file:io.github.seleniumquery.by.DriverVersionUtils.java

private static String getEmulatedBrowser(HtmlUnitDriver htmlUnitDriver) {
    try {//from w  w w  .  j  a v a2s.co m
        // #HtmlUnit #reflection #hack
        Method getWebClientMethod = HtmlUnitDriver.class.getDeclaredMethod("getWebClient");
        boolean wasAccessibleBefore = getWebClientMethod.isAccessible();
        getWebClientMethod.setAccessible(true);
        WebClient webClient = (WebClient) getWebClientMethod.invoke(htmlUnitDriver);
        getWebClientMethod.setAccessible(wasAccessibleBefore);
        return webClient.getBrowserVersion().toString();
    } catch (Exception e) {
        LOGGER.debug("Error while inspecting HtmlUnitDriver version.", e);
        return "";
    }
}

From source file:org.jruyi.cli.Main.java

private static void init() throws Throwable {
    ClassLoader classLoader = Main.class.getClassLoader();
    Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    boolean accessible = addUrl.isAccessible();
    if (!accessible)
        addUrl.setAccessible(true);// w w w. j  ava  2 s.  co m

    File[] jars = getLibJars();
    for (File jar : jars)
        addUrl.invoke(classLoader, jar.getCanonicalFile().toURI().toURL());

    if (!accessible)
        addUrl.setAccessible(false);
}

From source file:com.yanzhenjie.permission.DefaultRequest.java

private static void callbackAnnotation(Object callback, int requestCode,
        Class<? extends Annotation> annotationClass, List<String> permissions) {
    Method[] methods = findMethodForRequestCode(callback.getClass(), annotationClass, requestCode);
    if (methods.length == 0)
        Log.e(TAG, "Do you forget @PermissionYes or @PermissionNo for callback method ?");
    else//from w  w  w.j  a  v  a 2 s  .co m
        try {
            for (Method method : methods) {
                if (!method.isAccessible())
                    method.setAccessible(true);
                method.invoke(callback, permissions);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
}

From source file:org.springframework.batch.item.xml.StaxUtils.java

public static XMLEventWriter getXmlEventWriter(Result r) throws Exception {
    Method m = r.getClass().getDeclaredMethod("getXMLEventWriter", new Class[] {});
    boolean accessible = m.isAccessible();
    m.setAccessible(true);/*  w  ww  .  ja v  a2s  .  c o  m*/
    Object result = m.invoke(r);
    m.setAccessible(accessible);
    return (XMLEventWriter) result;
}

From source file:org.springframework.batch.item.xml.StaxUtils.java

public static XMLEventReader getXmlEventReader(Source s) throws Exception {
    Method m = s.getClass().getDeclaredMethod("getXMLEventReader", new Class[] {});
    boolean accessible = m.isAccessible();
    m.setAccessible(true);//w w w  .j a  v a 2  s  . c  om
    Object result = m.invoke(s);
    m.setAccessible(accessible);
    return (XMLEventReader) result;
}

From source file:Main.java

/**
 * Invokes the given method on the EDT./*from ww  w.j ava 2  s.co m*/
 *
 * @param target     Target object exposing the specified method.
 * @param methodName Method to invoke.
 * @param args       Arguments to pass to the method.
 */
public static void invokeOnEDT(final Object target, final String methodName, final Object... args) {
    final Class[] types = new Class[args.length];
    for (int i = 0; i < types.length; i++)
        types[i] = args[i].getClass();
    final Method m = getMethod(target, methodName, types);
    if (m == null)
        throw new RuntimeException("No such method: " + methodName + '(' + Arrays.toString(types)
                + ") found for target" + "class " + target.getClass().getName());
    if (!m.isAccessible())
        m.setAccessible(true);
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                m.invoke(target, args);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });
}

From source file:com.hurence.logisland.util.string.StringUtilsTest.java

/**
 * Sets an environment variable FOR THE CURRENT RUN OF THE JVM
 * Does not actually modify the system's environment variables,
 *  but rather only the copy of the variables that java has taken,
 *  and hence should only be used for testing purposes!
 * @param key The Name of the variable to set
 * @param value The value of the variable to set
 *//*from w  ww  .j  a v a 2  s.c om*/
@SuppressWarnings("unchecked")
public static <K, V> void setEnv(final String key, final String value) throws InvocationTargetException {
    try {
        /// we obtain the actual environment
        final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        final boolean environmentAccessibility = theEnvironmentField.isAccessible();
        theEnvironmentField.setAccessible(true);

        final Map<K, V> env = (Map<K, V>) theEnvironmentField.get(null);

        if (SystemUtils.IS_OS_WINDOWS) {
            // This is all that is needed on windows running java jdk 1.8.0_92
            if (value == null) {
                env.remove(key);
            } else {
                env.put((K) key, (V) value);
            }
        } else {
            // This is triggered to work on openjdk 1.8.0_91
            // The ProcessEnvironment$Variable is the key of the map
            final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable");
            final Method convertToVariable = variableClass.getMethod("valueOf", String.class);
            final boolean conversionVariableAccessibility = convertToVariable.isAccessible();
            convertToVariable.setAccessible(true);

            // The ProcessEnvironment$Value is the value fo the map
            final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value");
            final Method convertToValue = valueClass.getMethod("valueOf", String.class);
            final boolean conversionValueAccessibility = convertToValue.isAccessible();
            convertToValue.setAccessible(true);

            if (value == null) {
                env.remove(convertToVariable.invoke(null, key));
            } else {
                // we place the new value inside the map after conversion so as to
                // avoid class cast exceptions when rerunning this code
                env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value));

                // reset accessibility to what they were
                convertToValue.setAccessible(conversionValueAccessibility);
                convertToVariable.setAccessible(conversionVariableAccessibility);
            }
        }
        // reset environment accessibility
        theEnvironmentField.setAccessible(environmentAccessibility);

        // we apply the same to the case insensitive environment
        final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible();
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        // Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well
        final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        if (value == null) {
            // remove if null
            cienv.remove(key);
        } else {
            cienv.put(key, value);
        }
        theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility);
    } catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException
            | InvocationTargetException e) {
        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <" + value + ">",
                e);
    } catch (final NoSuchFieldException e) {
        // we could not find theEnvironment
        final Map<String, String> env = System.getenv();
        Stream.of(Collections.class.getDeclaredClasses())
                // obtain the declared classes of type $UnmodifiableMap
                .filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName())).map(c1 -> {
                    try {
                        return c1.getDeclaredField("m");
                    } catch (final NoSuchFieldException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + "> when locating in-class memory map of environment", e1);
                    }
                }).forEach(field -> {
                    try {
                        final boolean fieldAccessibility = field.isAccessible();
                        field.setAccessible(true);
                        // we obtain the environment
                        final Map<String, String> map = (Map<String, String>) field.get(env);
                        if (value == null) {
                            // remove if null
                            map.remove(key);
                        } else {
                            map.put(key, value);
                        }
                        // reset accessibility
                        field.setAccessible(fieldAccessibility);
                    } catch (final ConcurrentModificationException e1) {
                        // This may happen if we keep backups of the environment before calling this method
                        // as the map that we kept as a backup may be picked up inside this block.
                        // So we simply skip this attempt and continue adjusting the other maps
                        // To avoid this one should always keep individual keys/value backups not the entire map
                        System.out.println("Attempted to modify source map: " + field.getDeclaringClass() + "#"
                                + field.getName() + e1);
                    } catch (final IllegalAccessException e1) {
                        throw new IllegalStateException("Failed setting environment variable <" + key + "> to <"
                                + value + ">. Unable to access field!", e1);
                    }
                });
    }
    System.out.println(
            "Set environment variable <" + key + "> to <" + value + ">. Sanity Check: " + System.getenv(key));
}