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:kr.re.dev.LikeAA.LikeAA.java

@SuppressLint("HandlerLeak")
private void callAfterViews() {
    for (Method method : mAfterViewsMethods) {
        if (!method.isAccessible())
            method.setAccessible(true);/* ww w  . j  a va 2  s  . co m*/
        final WeakReference<Handler> waekHandler = new WeakReference<Handler>(
                new Handler(Looper.getMainLooper()) {
                    public void dispatchMessage(Message msg) {
                        Object target = mFinder.getTarget();
                        if (target == null)
                            return;
                        Method method = (Method) msg.obj;
                        try {
                            method.invoke(target, makeEmptyArgs(method.getParameterTypes()));
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            Thread.getDefaultUncaughtExceptionHandler()
                                    .uncaughtException(Looper.getMainLooper().getThread(), e);
                        }

                    };
                });
        Message msg = waekHandler.get().obtainMessage();
        msg.obj = method;
        waekHandler.get().sendMessage(msg);
        waekHandler.clear();
    }
}

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

/**
 * Pass in an empty map and it fills it with Key = Value for the source
 * object. It returns false if one or more key values are null, or if this
 * object has no keys defined//from   w  w w. java 2 s .co  m
 */
static boolean fillInKeys(String path, GraphDataObject source, GraphMapping mapping, Map map)
        throws InvocationTargetException, TransformException {
    try {
        Set keys = mapping.getKeyFields();
        boolean nullKey = false;
        if (keys == null || keys.size() == 0) {
            if (log.isDebugEnabled())
                log.debug("Object Has No KEYS! - " + source.getClass().getName());
            return false;
        }
        // Loop through all the keys get het the values
        for (Iterator k = keys.iterator(); k.hasNext();) {
            String keyField = (String) k.next();
            PropertyDescriptor pd = mapping.getDataFieldDescriptor(keyField);
            if (pd != null && pd.getReadMethod() != null) {
                Method m = pd.getReadMethod();
                if (!m.isAccessible())
                    m.setAccessible(true);
                Object value = m.invoke(source, new Object[] {});
                map.put(keyField, value);
                if (log.isDebugEnabled())
                    log.debug("Key " + keyField + "='" + value + "' on object '" + source.getClass().getName()
                            + '\'');
                if (value == null) {
                    nullKey = true;
                }
            } else {
                TransformException me = new TransformException(TransformException.NO_KEY_ON_OBJECT, path,
                        keyField, source.getClass().getName());
                log.error(me.getLocalizedMessage());
                throw me;
            }
        }
        return !nullKey;
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, path, e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
        //        } catch (InvocationTargetException e) {
        //            TransformException me = new TransformException(TransformException.INVOCATION_ERROR, path, e );
        //            log.error(me.getLocalizedMessage(),me.getCause());
        //            throw me;
    }
}

From source file:com.aftabsikander.permissionassist.PermissionAssistant.java

private static void runAnnotatedMethods(@NonNull Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();//from  w  ww . j ava2 s  .c o  m
    }

    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:de.matzefratze123.heavyspleef.core.flag.FlagRegistry.java

public void flushAndExecuteInitMethods() {
    while (!queuedInitMethods.isEmpty()) {
        Method method = queuedInitMethods.poll();

        boolean accessible = method.isAccessible();
        if (!accessible) {
            method.setAccessible(true);/*from w  ww  .  j a va  2  s. com*/
        }

        Class<?>[] parameters = method.getParameterTypes();
        Object[] args = new Object[parameters.length];

        for (int i = 0; i < parameters.length; i++) {
            Class<?> parameter = parameters[i];
            if (parameter == HeavySpleef.class) {
                args[i] = heavySpleef;
            }
        }

        try {
            method.invoke(null, args);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new IllegalArgumentException("Could not invoke flag initialization method " + method.getName()
                    + " of type " + method.getDeclaringClass().getCanonicalName() + ": ", e);
        } finally {
            method.setAccessible(accessible);
        }
    }
}

From source file:com.yanzhenjie.durban.Durban.java

/**
 * Start cropping.//from w w  w. j  a v  a  2  s  . com
 */
public void start() {
    try {
        Method method = o.getClass().getMethod("startActivityForResult", Intent.class, int.class);
        if (!method.isAccessible())
            method.setAccessible(true);
        method.invoke(o, mCropIntent, mCropIntent.getIntExtra("requestCode", 1));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.kogitune.launcher3.LauncherAppWidgetHostView.java

@Override
public void updateAppWidget(RemoteViews remoteViews) {
    if (EXPERIMENTAL) {
        if (remoteViews != null) {
            Handler mH = null;/* www. jav a2 s  . c  o  m*/
            Field queueField = null;
            MessageQueue messageQueue = null;
            try {
                Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
                Class[] params = new Class[0];
                Method currentActivityThread = activityThreadClass.getDeclaredMethod("currentActivityThread",
                        params);
                Boolean accessible = currentActivityThread.isAccessible();
                currentActivityThread.setAccessible(true);
                Object obj = currentActivityThread.invoke(activityThreadClass);
                if (obj == null) {
                    Log.d("ERROR", "The current activity thread is null!");
                }
                currentActivityThread.setAccessible(accessible);

                Field mHField = activityThreadClass.getDeclaredField("mH");
                mHField.setAccessible(true);
                mH = (Handler) mHField.get(obj);
                queueField = Handler.class.getDeclaredField("mQueue");
                queueField.setAccessible(true);
                messageQueue = (MessageQueue) queueField.get(mH);

                HandlerThread handlerThread = new HandlerThread("other");
                handlerThread.start();
                handlerThread.quit();
                queueField.set(mH, null);

            } catch (Exception e) {
                Log.d("ERROR", Log.getStackTraceString(e));
            }
            Context context = getContext().getApplicationContext();
            NotificationManager notificationManager = (NotificationManager) context.getApplicationContext()
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setContent(remoteViews).setSmallIcon(R.drawable.ic_launcher_info_normal_holo)
                    .setContentTitle("My notification") // ?
                    .setContentText("Hello Notification!!"); // ?

            Notification notification = builder.build();
            notificationManager.notify(getAppWidgetId(), notification);

            final Field finalQueueField = queueField;
            final Handler finalMH = mH;
            final MessageQueue finalMessageQueue = messageQueue;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(50L);
                        if (finalMessageQueue != null)
                            finalQueueField.set(finalMH, finalMessageQueue);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }
    }
    // Store the orientation in which the widget was inflated
    mPreviousOrientation = mContext.getResources().getConfiguration().orientation;
    super.updateAppWidget(remoteViews);
}

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

/**
 * Display the properties of this JavaBean in XML format.
 *
 * @param source Javabean who's contents should be printed
 * @return XML formatted string of this beans properties and their values
 *//*  ww  w  .ja v  a2 s.  c  om*/
public static String printXMLGraph(Object source) {

    StringBuffer out = new StringBuffer();
    out.append("<" + source.getClass().getSimpleName() + ">");

    try {
        BeanInfo sInfo = Introspector.getBeanInfo(source.getClass());
        PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors();
        if (sDescriptors != null && sDescriptors.length != 0) {
            for (int i = 0; i < sDescriptors.length; i++) {
                PropertyDescriptor sDesc = sDescriptors[i];
                Method sm = sDesc.getReadMethod();
                if (sm != null && sDesc.getWriteMethod() != null) {
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    Object sValue = sm.invoke(source, (Object[]) null);

                    out.append("<" + sDesc.getName() + ">");

                    if (sValue != null && !sm.getReturnType().isArray()
                            && !GraphDataObject.class.isAssignableFrom(sValue.getClass())) {
                        out.append(sValue.toString().trim());
                    }
                    out.append("</" + sDesc.getName() + ">");
                }
            }
        }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    } catch (InvocationTargetException e) {
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e);
        log.error(me.getLocalizedMessage(), me.getCause());
        //throw me;
    } catch (IntrospectionException e) {
        TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???",
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    }
    out.append("</" + source.getClass().getSimpleName() + ">");
    return out.toString();
}

From source file:com.googlecode.loosejar.ClassLoaderAnalyzer.java

@SuppressWarnings("unchecked")
private Enumeration<URL> findManifestResources() {
    //invoke #findResource(String) method reflectively as it is protected in java.lang.ClassLoader
    try {//from   ww  w . ja v  a  2  s .  co  m
        Method method = findMethod(classLoader.getClass(), "findResources", new Class<?>[] { String.class });

        //attempt to disable security check for non-public methods.
        if (!Modifier.isPublic(method.getModifiers()) && !method.isAccessible()) {
            method.setAccessible(true);
        }

        // This will return a transitive closure of all jars on the classpath
        // in the form of
        // jar:file:/foo/bar/baz.jar!/META-INF/MANIFEST.MF
        return (Enumeration<URL>) method.invoke(classLoader, "META-INF/MANIFEST.MF");

    } catch (IllegalAccessException e) {
        log("Failed to invoke #findResources(String) method on classloader [" + classLoader + "]. "
                + "No access permissions.");
    } catch (InvocationTargetException e) {
        log("Failed to invoke #findResources(String) method on classloader [" + classLoader + "]. "
                + "The classloader is likely no longer available.");
    }
    return null;
}

From source file:org.apache.sling.performance.FrameworkPerformanceMethod.java

/**
 * Recursively call a specific method annotated with a custom annotation
 *
 * @param test/*from   w  w  w.j a va  2 s. c o  m*/
 *            the test class that contains the method
 * @param instance
 *            the instance on which will run the method
 * @param methodAnnotation
 *            the method annotation to look for
 * @throws InvocationTargetException
 * @throws InvalidAttributesException
 * @throws IllegalAccessException
 * @throws InstantiationException
 */
@SuppressWarnings({ "rawtypes" })
private void recursiveCallSpecificMethod(Class test, Object instance,
        Class<? extends Annotation> methodAnnotation) throws InvocationTargetException,
        InvalidAttributesException, IllegalAccessException, InstantiationException {
    if (test.getSuperclass() != null) {
        recursiveCallSpecificMethod(test.getSuperclass(), instance, methodAnnotation);
    }

    Method testMethod = getSpecificTestMethod(test, methodAnnotation);
    if (testMethod != null) {
        if (!testMethod.isAccessible()) {
            testMethod.setAccessible(true);
        }
        testMethod.invoke(instance);
    }
}

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

/**
 * Same as printGraph(Object source), except the objectStack lists all the parent
 * objects its printed, and if this is one of them, it stops. This allows detection
 * of possible infinite recusion./* w  ww  . j a  va 2 s  .co  m*/
 *
 * @param source      Javabean who's contents should be printed
 * @param objectStack List of objects already traversed
 * @return multi-line string of this beans properties and their values
 */
public static String printGraph(Object source, List objectStack) {
    if (source == null)
        return null;

    // Prevent infinite object recursion
    if (objectStack != null)
        if (objectStack.contains(source))
            return "Object Already Used. " + source.getClass().getName() + '@' + source.hashCode();
        else
            objectStack.add(source);
    else {
        objectStack = new ArrayList();
        objectStack.add(source);
    }

    StringBuffer out = new StringBuffer();
    out.append(source.getClass().getName());
    out.append("\n");

    try {
        BeanInfo sInfo = Introspector.getBeanInfo(source.getClass());
        PropertyDescriptor[] sDescriptors = sInfo.getPropertyDescriptors();
        if (sDescriptors != null && sDescriptors.length != 0)
            for (int i = 0; i < sDescriptors.length; i++) {
                PropertyDescriptor sDesc = sDescriptors[i];
                Method sm = sDesc.getReadMethod();
                if (sm != null && sDesc.getWriteMethod() != null) {
                    if (!sm.isAccessible())
                        sm.setAccessible(true);
                    Object sValue = sm.invoke(source, (Object[]) null);

                    out.append("  ");
                    out.append(sDesc.getName());
                    if (source instanceof GraphDataObject) {
                        if (((GraphDataObject) source).hasChanged(sDesc.getName()))
                            out.append('*');
                    }
                    out.append('=');
                    if (sValue == null)
                        out.append("<--NULL-->\n");
                    else if (sm.getReturnType().isArray()
                            && !sm.getReturnType().getComponentType().isPrimitive()) {
                        StringBuffer out2 = new StringBuffer();
                        out2.append("Array of ");
                        out2.append(sm.getReturnType().getComponentType().getName());
                        out2.append("\n");
                        // Loop through array
                        Object[] a = (Object[]) sValue;
                        for (int j = 0; j < a.length; j++) {
                            out2.append('[');
                            out2.append(j);
                            out2.append("] ");
                            if (a[j] == null)
                                out2.append("<--NULL-->");
                            else if (GraphDataObject.class.isAssignableFrom(a[j].getClass()))
                                out2.append(((GraphDataObject) a[j]).toString(objectStack));
                            else
                                //out2.append(StringHelper.linePad(a[j].toString(), 4, " ",true));
                                out2.append(a[j].toString());
                        }
                        out.append(StringHelper.linePad(out2.toString(), 4, " ", true));
                    } else {
                        if (GraphDataObject.class.isAssignableFrom(sValue.getClass()))
                            out.append(StringHelper.linePad(((GraphDataObject) sValue).toString(objectStack), 4,
                                    " ", true));
                        else {
                            out.append(StringHelper.linePad(sValue.toString(), 4, " ", true));
                            out.append("\n");
                        }

                    }
                }
            }
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, "???", e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    } catch (InvocationTargetException e) {
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, "???", e);
        log.error(me.getLocalizedMessage(), me.getCause());
        //throw me;
    } catch (IntrospectionException e) {
        TransformException me = new TransformException(TransformException.INTROSPECT_ERROR, "???",
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        //throw me;
    }
    return out.toString();
}