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:cn.finalteam.galleryfinal.permission.EasyPermissions.java

private static void runAnnotatedMethods(Object object, int requestCode) {
    Class clazz = object.getClass();
    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 non-void method " + method.getName());
                }/* w  ww  .  ja  v a 2 s.c om*/

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

From source file:com.ybg.rp.assistant.permission.EasyPermissions.java

private static void runAnnotatedMethods(Object object, int requestCode) {
    Class clazz = object.getClass();
    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 non-void method " + method.getName());
                }//from  w ww. j av  a2s .  c  o  m

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

From source file:com.austin.base.commons.util.ReflectUtil.java

/**
 * @param object//from   ww  w. ja v a2  s  .  c o  m
 * @param methodName
 * @param params
 * @return
 * @throws NoSuchMethodException
 */
public static Object invokePrivateMethod(Object object, String methodName, Object... params)
        throws NoSuchMethodException {
    Assert.notNull(object);
    Assert.hasText(methodName);
    Class[] types = new Class[params.length];
    for (int i = 0; i < params.length; i++) {
        types[i] = params[i].getClass();
    }

    Class clazz = object.getClass();
    Method method = null;
    for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) {
        try {
            method = superClass.getDeclaredMethod(methodName, types);
            break;
        } catch (NoSuchMethodException e) {
            // ??17,?
        }
    }

    if (method == null)
        throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName);

    boolean accessible = method.isAccessible();
    method.setAccessible(true);
    Object result = null;
    try {
        result = method.invoke(object, params);
    } catch (Exception e) {
        ReflectionUtils.handleReflectionException(e);
    }
    method.setAccessible(accessible);
    return result;
}

From source file:com.github.shareme.blackandroids.greenandroid.easpermissions.EasyPermissions.java

private static void runAnnotatedMethods(Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();//from  w  w w  .j  a  v a  2  s .  c o  m
    }
    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 non-void method " + method.getName());
                }

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

From source file:com.are.photophone.utils.permissionutils.EasyPermissions.java

private static void runAnnotatedMethods(Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();/* www.  j a v a  2 s . co m*/
    }
    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 non-void method " + method.getName());
                }

                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);
                }
            }
        }
    }
}

From source file:Main.java

public static <T extends Object, Result> Result callMethodCast(T receiver, Class<Result> resultClass,
        String methodName, Object... args) throws NoSuchMethodException, IllegalAccessException,
        InvocationTargetException, InstantiationException {
    if (receiver == null || methodName == null) {
        return null;
    }// w  w w .j a  v  a  2 s.  com
    Class<?> cls = receiver.getClass();
    Method toInvoke = null;
    do {
        Method[] methods = cls.getDeclaredMethods();
        methodLoop: for (Method method : methods) {
            if (!methodName.equals(method.getName())) {
                continue;
            }
            Class<?>[] paramTypes = method.getParameterTypes();
            if (args == null && paramTypes == null) {
                toInvoke = method;
                break;
            } else if (args == null || paramTypes == null || paramTypes.length != args.length) {
                continue;
            }

            for (int i = 0; i < args.length; ++i) {
                if (!paramTypes[i].isAssignableFrom(args[i].getClass())) {
                    continue methodLoop;
                }
            }
            toInvoke = method;
        }
    } while (toInvoke == null && (cls = cls.getSuperclass()) != null);
    Result t;
    if (toInvoke != null) {
        boolean accessible = toInvoke.isAccessible();
        toInvoke.setAccessible(true);
        if (resultClass != null) {
            t = resultClass.cast(toInvoke.invoke(receiver, args));
        } else {
            toInvoke.invoke(receiver, args);
            t = null;
        }
        toInvoke.setAccessible(accessible);
        return t;
    } else {
        throw new NoSuchMethodException("Method " + methodName + " not found");
    }
}

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

/**
 * Take a source object and try and mold it back it its domain object
 *
 * @param path    The path of this object being processed. This identifies possible parent and/or indexed entries where this object is contained.
 * @param source  Source object to mould from, typically a GraphDataObject
 * @param uow     Transaction handle all creates/update will be performed within. Throws an exception if null.
 * @param handler Possible bean handler to be used when processing this source object graph
 * @return In VALIDATE_ONLY mode the source object will be returned with default data. Else a GraphDataObject with just the key-fields of the root object will be returned if that object was newly created. Else a null will be returned.
 * @throws ApplicationExceptions Thrown if one or more application logic errors are generated during moulding
 * @throws FrameworkException    Thrown if any runtime moulding error has occured.
 *//*from  w w  w . ja v  a 2s.  c o  m*/
private static GraphDataObject updateGraph(String path, GraphDataObject source, UOW uow,
        ITransformationHandler handler, Mode mode, GraphDataObject newGraph)
        throws ApplicationExceptions, FrameworkException {
    if (log.isDebugEnabled())
        log.debug("Update Bean " + path);
    if (source.getDeleteObject() != null && source.getDeleteObject()) {
        if (mode == Mode.VALIDATE_ONLY) {
            if (log.isDebugEnabled())
                log.debug(
                        "The 'deleteObject' property is true. No prevalidations will be performed. The input object will be returned as is.");
            return source;
        } else {
            if (log.isDebugEnabled())
                log.debug("The 'deleteObject' property is true. Invoking deleteGraph()");
            deleteGraph(path, source, uow, handler);
            return null;
        }
    } else {
        try {
            IPersistent domainObject = null;
            GraphMapping mapping = MappingFactory.getInstance(source);
            Map keys = new LinkedHashMap();
            Class doClass = mapping.getDomainClass();

            // Get the key fields used in the domain object
            // In CLONE mode, get the keys from the new graph, and force the creation of the domain object
            boolean gotKeys = false;
            if (mode == Mode.CLONE) {
                if (newGraph != null)
                    gotKeys = TransformerUtils.fillInKeys(path, newGraph, mapping, keys);
            } else
                gotKeys = TransformerUtils.fillInKeys(path, source, mapping, keys);

            // read DO based on key
            if (gotKeys) {
                // get the method on the DO to read via PK
                Method[] ma = doClass.getMethods();
                Method findByPK = null;
                for (int i = 0; i < ma.length; i++) {
                    if (ma[i].getName().equals("findByPK")) {
                        if (ma[i].getParameterTypes().length == (keys.size() + 1)
                                && (ma[i].getParameterTypes())[0] == UOW.class) {
                            // Found with name and correct no. of input params
                            findByPK = ma[i];
                            break;
                        }
                    }
                }
                if (findByPK == null)
                    throw new ApplicationExceptions(
                            new DomainObjectNotFoundException(TransformerUtils.findDomainLabel(doClass)));

                // Build input array
                Object[] inputs = new Object[keys.size() + 1];
                {
                    inputs[0] = uow;
                    int i = 1;
                    for (Iterator it = keys.values().iterator(); it.hasNext(); i++) {
                        inputs[i] = it.next();
                    }
                }

                // Find Object based on key
                domainObject = (IPersistent) findByPK.invoke(null, inputs);

                if (domainObject != null && mode == Mode.CLONE)
                    throw new ApplicationExceptions(
                            new DuplicateKeyException(TransformerUtils.findDomainLabel(doClass)));

            } else {
                if (log.isDebugEnabled())
                    log.debug("Object " + path
                            + " has either missing or null key values - Assume Create is needed");
            }

            // Create object if not found
            boolean createMode = false;
            if (domainObject == null) {
                // In MASS_UPDATE mode, error if DO not found
                if (mode == Mode.MASS_UPDATE)
                    throw new ApplicationExceptions(
                            new DomainObjectNotFoundException(TransformerUtils.findDomainLabel(doClass)));

                // NEW OBJECT, create and reflect keys
                if (log.isDebugEnabled())
                    log.debug("DO '" + mapping.getDomainClassShortName()
                            + "' not found with key, create a new one...");
                domainObject = (IPersistent) doClass.newInstance();
                // set the key fields
                for (Iterator it = keys.keySet().iterator(); it.hasNext();) {
                    String keyField = (String) it.next();
                    if (mapping.isReadOnly(keyField))
                        continue;
                    Object value = keys.get(keyField);
                    TransformerUtils.updateProperty(mapping.getDomainFieldDescriptor(keyField), value,
                            domainObject);
                }
                createMode = true;
            } else {
                if (log.isDebugEnabled())
                    log.debug("Found DO '" + mapping.getDomainClassShortName() + "' with key,");
            }

            // Now update all domain fields
            TransformerUtils.updateBeanData(path, source, uow, handler, mapping, domainObject, mode, newGraph);

            // Invoke the changeDone trigger
            if (handler != null && handler.isChangeDone()) {
                for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                    transformationHandler.changeDone(path, source, domainObject, uow);
                }
            }

            // Return an appropriate output
            if (mode == Mode.VALIDATE_ONLY) {
                // In VALIDATE_ONLY mode, return the input graph (with defaulted data)
                return source;
            } else if (createMode) {
                // In create-mode, Create a new graph and stamp just the keys
                GraphDataObject outputGraph = source.getClass().newInstance();
                for (Iterator i = keys.keySet().iterator(); i.hasNext();) {
                    String keyField = (String) i.next();
                    PropertyDescriptor pd = mapping.getDomainFieldDescriptor(keyField);
                    if (pd != null && pd.getReadMethod() != null) {
                        Method m = pd.getReadMethod();
                        if (!m.isAccessible())
                            m.setAccessible(true);
                        Object value = m.invoke(domainObject, (Object[]) null);
                        AccessibleObject accessibleObject = mapping.getDataMutator(keyField);
                        setValue(accessibleObject, outputGraph, value);
                    } else {
                        TransformException me = new TransformException(TransformException.NO_KEY_ON_OBJECT,
                                path, keyField, source.getClass().getName());
                        log.error(me.getLocalizedMessage());
                        throw me;
                    }
                }
                return outputGraph;
            } else {
                // In update-mode, return a null
                return null;
            }
        } catch (IllegalAccessException e) {
            TransformException me = new TransformException(TransformException.ACCESS_ERROR, path,
                    e.getMessage());
            log.error(me.getLocalizedMessage(), e);
            throw me;
        } catch (InvocationTargetException e) {
            ApplicationExceptions appExps = ExceptionHelper.extractApplicationExceptions(e);
            if (appExps != null)
                throw appExps;
            FrameworkException fe = ExceptionHelper.extractFrameworkException(e);
            if (fe != null)
                throw fe;
            TransformException me = new TransformException(TransformException.INVOCATION_ERROR, path, e);
            log.error(me.getLocalizedMessage(), me.getCause());
            throw me;
        } catch (InstantiationException e) {
            TransformException me = new TransformException(TransformException.INSTANTICATION_ERROR, path,
                    e.getMessage());
            log.error(me.getLocalizedMessage(), e);
            throw me;
        }
    }
}

From source file:org.sglj.service.rmi.server.NotificationServiceStub.java

public NotificationServiceStub(NotificationSender<T> notificationSender) {
    this.sender = notificationSender;

    Method[] methods = this.getClass().getDeclaredMethods();
    Set<Method> set = new HashSet<Method>();
    for (Method m : methods) {
        if (!m.isAccessible()) {
            try {
                m.setAccessible(true);/*from  www.j a va  2  s  .  c  om*/
            } catch (SecurityException ignorable) {
            }
        }
        RemoteMethod annot = m.getAnnotation(RemoteMethod.class);
        if (annot != null && annot.value() == RemoteMethod.RemoteMethodSide.CALLER
                && m.getReturnType() == void.class) {
            set.add(m);
        }
    }
    this.remoteMethods = Collections.unmodifiableSet(set);
}

From source file:org.apache.hadoop.io.retry.RetryInvocationHandler.java

private Object invokeMethod(Method method, Object[] args) throws Throwable {
    try {/*  w w w .  ja v a 2  s. c  o m*/
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        return method.invoke(implementation, args);
    } catch (InvocationTargetException e) {
        throw e.getCause();
    }
}

From source file:de.matzefratze123.heavyspleef.core.event.EventListenerMethod.java

@SuppressWarnings("unchecked")
public EventListenerMethod(Object instance, Method method) {
    this.instance = instance;
    this.method = method;

    if (!method.isAccessible()) {
        method.setAccessible(true);//  w  w  w. j  a v  a 2  s. c o  m
    }

    Class<?>[] parameters = method.getParameterTypes();
    Validate.isTrue(parameters.length == 1,
            "method must have only one parameter which must be a subtype of GameEvent");

    Class<?> eventClass = parameters[0];
    Validate.isTrue(GameEvent.class.isAssignableFrom(eventClass),
            "First parameter of method must be a subtype of GameEvent");

    this.eventClass = (Class<? extends GameEvent>) eventClass;
}