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:hr.ws4is.websocket.WebSocketOperations.java

private ExtJSResponse executeBean(final Bean<?> bean, final AnnotatedMethod<?> method, final Object[] params) {
    ExtJSResponse response = null;/*w  w w .  ja va 2s  . c  o m*/
    IDestructibleBeanInstance<?> di = null;

    try {
        di = beanManagerUtil.getDestructibleBeanInstance(bean);
        final Object beanInstance = di.getInstance();
        final Method javaMethod = method.getJavaMember();
        if (javaMethod.isAccessible()) {
            javaMethod.setAccessible(true);
        }

        response = (ExtJSResponse) javaMethod.invoke(beanInstance, params);

    } catch (Exception e) {
        response = new ExtJSResponse(e, e.getMessage());
    } finally {
        if (di != null) {
            di.release();
        }
    }

    return response;
}

From source file:candr.yoclip.option.AbstractSetterOption.java

protected void set(final T bean, final Value<T> value) {

    final Method setter = getSetter();

    boolean resetFieldAccessibility = false;
    try {// www  . jav a 2  s. com

        if (!setter.isAccessible()) {
            setter.setAccessible(true);
            resetFieldAccessibility = true;
        }

        value.set(bean, setter);

    } catch (Exception e) {
        if (e instanceof OptionsParseException) {
            throw (OptionsParseException) e;
        }
        throw new OptionsParseException("Error setting value " + getUniqueId(), e);

    } finally {
        if (resetFieldAccessibility) {
            setter.setAccessible(false);
        }
    }
}

From source file:org.jaffa.soa.dataaccess.TransformerUtils.java

static Object getProperty(PropertyDescriptor pd, Object source)
        throws IllegalAccessException, InvocationTargetException, TransformException {
    if (pd != null && pd.getReadMethod() != null) {
        Method m = pd.getReadMethod();
        if (!m.isAccessible())
            m.setAccessible(true);/*  w w  w .j a v  a 2  s.  c o m*/
        Object value = m.invoke(source, new Object[] {});
        if (log.isDebugEnabled())
            log.debug("Get property '" + pd.getName() + '=' + value + "' on object '"
                    + source.getClass().getName() + '\'');
        return value;
    } else {
        TransformException me = new TransformException(TransformException.NO_GETTER, null,
                pd == null ? "???" : pd.getName(), source.getClass().getName());
        log.error(me.getLocalizedMessage());
        throw me;
    }
}

From source file:plugin.google.maps.Environment.java

@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) {
    cordova.getThreadPool().submit(new Runnable() {
        @Override/* w  ww . jav  a2s  .c om*/
        public void run() {
            try {
                Method method = Environment.this.getClass().getDeclaredMethod(action, JSONArray.class,
                        CallbackContext.class);
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }
                method.invoke(Environment.this, args, callbackContext);
            } catch (Exception e) {
                Log.e("CordovaLog", "An error occurred", e);
                callbackContext.error(e.toString());
            }
        }
    });

    return true;
}

From source file:org.cloudfoundry.identity.statsd.UaaMetricsEmitter.java

public Number getValueFromBean(Object mbean, String getter) {
    Method method = findMethod(mbean.getClass(), getter);
    if (method != null) {
        boolean original = method.isAccessible();
        method.setAccessible(true);/*from ww w  .ja  va2  s  .co  m*/
        try {
            return (Number) ReflectionUtils.invokeMethod(method, mbean);
        } catch (Exception e) {
            logger.debug("Unable to invoke metric", e);
        } finally {
            method.setAccessible(original);
        }

    }
    return null;
}

From source file:org.jaffa.soa.dataaccess.TransformerUtils.java

static void setProperty(PropertyDescriptor pd, Object value, Object source)
        throws IllegalAccessException, InvocationTargetException, TransformException {
    if (pd != null && pd.getWriteMethod() != null) {
        Method m = pd.getWriteMethod();
        if (!m.isAccessible())
            m.setAccessible(true);/*from w  w  w .j  a  va  2s  .  com*/
        Class tClass = m.getParameterTypes()[0];
        if (value == null || tClass.isAssignableFrom(value.getClass())) {
            m.invoke(source, new Object[] { value });
            if (log.isDebugEnabled())
                log.debug("Set property '" + pd.getName() + '=' + value + "' on object '"
                        + source.getClass().getName() + '\'');
        } else if (DataTypeMapper.instance().isMappable(value.getClass(), tClass)) {
            // See if there is a datatype mapper for these classes
            value = DataTypeMapper.instance().map(value, tClass);
            m.invoke(source, new Object[] { value });
            if (log.isDebugEnabled())
                log.debug("Translate+Set property '" + pd.getName() + '=' + value + "' on object '"
                        + source.getClass().getName() + '\'');
        } else {
            // Data type mismatch
            throw new TransformException(TransformException.DATATYPE_MISMATCH,
                    source.getClass().getName() + '.' + m.getName(), tClass.getName(),
                    value.getClass().getName());
        }
    } else {
        TransformException me = new TransformException(TransformException.NO_SETTER, null,
                pd == null ? "???" : pd.getName(), source.getClass().getName());
        log.error(me.getLocalizedMessage());
        throw me;
    }
}

From source file:org.echocat.redprecursor.annotations.utils.AccessAlsoProtectedMembersReflectivePropertyAccessor.java

@Override
protected Method findGetterForProperty(String propertyName, Class<?> clazz, boolean mustBeStatic) {
    Method result = null;/*from w  w w.  j av  a2s .c  o m*/
    final PropertyDescriptor propertyDescriptor = findPropertyDescriptorFor(clazz, propertyName);
    if (propertyDescriptor != null) {
        result = propertyDescriptor.getReadMethod();
    }
    if (result == null) {
        Class<?> current = clazz;
        final String getterName = "get" + StringUtils.capitalize(propertyName);
        while (result == null && !Object.class.equals(current)) {
            try {
                final Method potentialMethod = current.getDeclaredMethod(getterName);
                if (!mustBeStatic || Modifier.isStatic(potentialMethod.getModifiers())) {
                    if (!potentialMethod.isAccessible()) {
                        potentialMethod.setAccessible(true);
                    }
                    result = potentialMethod;
                }
            } catch (NoSuchMethodException ignored) {
            }
            current = current.getSuperclass();
        }
    }
    return result;
}

From source file:org.seasar.mayaa.impl.cycle.script.rhino.RhinoUtil.java

/**
 * getter??????//from  w ww.  j  ava 2  s  .  c om
 * JavaBean????????
 *
 * @param bean ?
 * @param propertyName ??
 * @return ?????????null
 * @throws NoSuchMethodException getter??????
 */
protected static Object getWithGetterMethod(Object bean, String propertyName) throws NoSuchMethodException {
    Class beanClass = bean.getClass();
    String baseName = capitalizePropertyName(propertyName);
    Method getter = null;
    try {
        getter = beanClass.getMethod("get" + baseName, VOID_ARGS_CLASS);
    } catch (NoSuchMethodException ignore) {
        // try boolean
    }
    if (getter == null) {
        try {
            // TODO Method
            Method booleanGetter = beanClass.getMethod("is" + baseName, VOID_ARGS_CLASS);
            if (booleanGetter != null) {
                Class returnType = booleanGetter.getReturnType();
                if (returnType.equals(Boolean.class) || returnType.equals(Boolean.TYPE)) {
                    getter = booleanGetter;
                }
            }
        } catch (NoSuchMethodException ignore) {
            // throw new exception for "getXxx"
        }
    }
    if (getter == null || Modifier.isPublic(getter.getModifiers()) == false) {
        throw new NoSuchMethodException(beanClass.toString() + ".get" + baseName + "()");
    }

    if (getter.isAccessible() == false) {
        getter.setAccessible(true);
    }
    try {
        return getter.invoke(bean, null);
    } catch (IllegalAccessException e) {
        LOG.debug(StringUtil.getMessage(RhinoUtil.class, 1, propertyName, beanClass.getName()));
    } catch (InvocationTargetException e) {
        LOG.debug(StringUtil.getMessage(RhinoUtil.class, 1, propertyName, beanClass.getName()));
    }
    return null;
}

From source file:com.zhangwx.dynamicpermissionsrequest.permission.EasyPermissions.java

private static void runAnnotatedMethods(@NonNull Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();//from w w w. ja v a2  s.c om
    }

    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(AfterPermissionGranted.class)) {
                // Check for annotated methods with matching request code.
                AfterPermissionGranted ann = method.getAnnotation(AfterPermissionGranted.class);
                if (ann.value() == requestCode) {
                    // Method must be void so that we can invoke it
                    if (method.getParameterTypes().length > 0) {
                        throw new RuntimeException("Cannot execute method " + method.getName()
                                + " because it is non-void method and/or has input parameters.");
                    }

                    try {
                        // Make method accessible if private
                        if (!method.isAccessible()) {
                            method.setAccessible(true);
                        }
                        method.invoke(object);
                    } catch (IllegalAccessException e) {
                        Log.e(TAG, "runDefaultMethod:IllegalAccessException", e);
                    } catch (InvocationTargetException e) {
                        Log.e(TAG, "runDefaultMethod:InvocationTargetException", e);
                    }
                }
            }
        }

        clazz = clazz.getSuperclass();
    }
}

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

public void init(String[] args) throws Exception {
    ClassLoader classLoader = Main.class.getClassLoader();
    if (!(classLoader instanceof URLClassLoader))
        classLoader = new URLClassLoader(new URL[0], classLoader);

    final Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    boolean accessible = addUrl.isAccessible();
    if (!accessible)
        addUrl.setAccessible(true);/*from w  w w . jav a  2s.c  om*/

    final ArrayList<String> pkgList = new ArrayList<>();
    final File[] jars = getLibJars();
    for (final File jar : jars) {
        final String exportPackages;
        try (JarFile jf = new JarFile(jar)) {
            exportPackages = jf.getManifest().getMainAttributes().getValue("Export-Package");
        }
        if (exportPackages != null)
            pkgList.add(exportPackages);
        addUrl.invoke(classLoader, jar.getCanonicalFile().toURI().toURL());
    }

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

    final int n = pkgList.size();
    if (n < 1)
        return;

    final StringBuilder builder = new StringBuilder(pkgList.get(0));
    for (int i = 1; i < n; ++i)
        builder.append(',').append(pkgList.get(i));

    final HashMap<String, String> props = new HashMap<>(3);
    props.put(Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, builder.toString());

    final Class<?> clazz = classLoader.loadClass("org.jruyi.system.main.Ruyi");
    final Object ruyi = clazz.getMethod("getInstance").invoke(null);
    clazz.getMethod("setProperties", Map.class).invoke(ruyi, props);
    final String instConfUrl = (String) clazz.getMethod(RUYI_PROPERTY, String.class).invoke(ruyi,
            JRUYI_INST_CONF_URL);

    System.setProperty(ShutdownCallbackRegistry.SHUTDOWN_CALLBACK_REGISTRY, Log4jCallback.class.getName());
    final String confFile = System.getProperty(LOG4J_CONF);
    if (confFile == null || confFile.trim().isEmpty())
        System.setProperty(LOG4J_CONF, instConfUrl + "log4j2.xml");

    m_ruyi = ruyi;
}