Java Code Examples for java.lang.reflect.Method.isAccessible()

The following are Jave code examples for showing how to use isAccessible() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: SerializationMethodInvoker.java   View Source Code Vote up 6 votes
private Method getMethod(final Class<?> type, final String name, final Class<?>... parameterTypes) {
    if (type == null) {
        return null;
    }
    final FastField method = new FastField(type, name);
    Method result = cache.get(method);

    if (result == null) {
        try {
            result = type.getDeclaredMethod(name, parameterTypes);
            if (!result.isAccessible()) {
                result.setAccessible(true);
            }
        } catch (final NoSuchMethodException e) {
            result = getMethod(type.getSuperclass(), name, parameterTypes);
        }
        cache.put(method, result);
    }
    return result;
}
 
Example 2
Project: GitHub   File: ShareReflectUtil.java   View Source Code Vote up 6 votes
/**
 * Locates a given method anywhere in the class inheritance hierarchy.
 *
 * @param instance       an object to search the method into.
 * @param name           method name
 * @param parameterTypes method parameter types
 * @return a method object
 * @throws NoSuchMethodException if the method cannot be located
 */
public static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
    throws NoSuchMethodException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);

            if (!method.isAccessible()) {
                method.setAccessible(true);
            }

            return method;
        } catch (NoSuchMethodException e) {
            // ignore and search next
        }
    }

    throw new NoSuchMethodException("Method "
        + name
        + " with parameters "
        + Arrays.asList(parameterTypes)
        + " not found in " + instance.getClass());
}
 
Example 3
Project: springreplugin   File: ReflectUtils.java   View Source Code Vote up 6 votes
public static Object invokeMethod(Method method, Object methodReceiver, Object... methodParamValues) throws
        InvocationTargetException, IllegalAccessException {

    if (method != null) {
        boolean acc = method.isAccessible();

        if (!acc) {
            method.setAccessible(true);
        }

        Object ret = method.invoke(methodReceiver, methodParamValues);

        if (!acc) {
            method.setAccessible(false);
        }

        return ret;
    }

    return null;
}
 
Example 4
Project: jvm-sandbox   File: SandboxReflectUtils.java   View Source Code Vote up 6 votes
/**
 * 定义类
 *
 * @param loader         目标ClassLoader
 * @param javaClassName  类名称
 * @param classByteArray 类字节码数组
 * @return 定义的类
 * @throws InvocationTargetException 目标方法调用发生异常
 * @throws IllegalAccessException    目标方法不可进入
 */
public static Class<?> defineClass(final ClassLoader loader,
                                   final String javaClassName,
                                   final byte[] classByteArray) throws InvocationTargetException, IllegalAccessException {

    final Method defineClassMethod =
            unCaughtGetClassDeclaredJavaMethod(ClassLoader.class, "defineClass", String.class, byte[].class, int.class, int.class);

    synchronized (defineClassMethod) {
        final boolean acc = defineClassMethod.isAccessible();
        try {
            defineClassMethod.setAccessible(true);
            return (Class<?>) defineClassMethod.invoke(
                    loader,
                    javaClassName,
                    classByteArray,
                    0,
                    classByteArray.length
            );
        } finally {
            defineClassMethod.setAccessible(acc);
        }
    }

}
 
Example 5
Project: ChocoPie   File: Reflector.java   View Source Code Vote up 6 votes
public static Object getValue(Object object, Method method, Object... params) throws ReflectorException, IllegalAccessException {
    boolean originalAccessibility = method.isAccessible();
    method.setAccessible(true);

    try {
        Object value = null;

        if (params != null && params.length > 0) {
            value = method.invoke(object, params);
        } else {
            value = method.invoke(object);
        }

        return value;
    } catch (InvocationTargetException e) {
        throw new ReflectorException("Unable to invoke selected method.", e);
    } finally {
        method.setAccessible(originalAccessibility);
    }
}
 
Example 6
Project: TPlayer   File: DelegateApplication64Bit.java   View Source Code Vote up 6 votes
private static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
        throws NoSuchMethodException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);


            if (!method.isAccessible()) {
                method.setAccessible(true);
            }

            return method;
        } catch (NoSuchMethodException e) {
            // ignore and search next
        }
    }

    throw new NoSuchMethodException("Method " + name + " with parameters " +
            Arrays.asList(parameterTypes) + " not found in " + instance.getClass());
}
 
Example 7
Project: r8   File: MultiDex.java   View Source Code Vote up 6 votes
/**
 * Locates a given method anywhere in the class inheritance hierarchy.
 *
 * @param instance an object to search the method into.
 * @param name method name
 * @param parameterTypes method parameter types
 * @return a method object
 * @throws NoSuchMethodException if the method cannot be located
 */
private static Method findMethod(Object instance, String name, Class<?>... parameterTypes)
        throws NoSuchMethodException {
    for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        try {
            Method method = clazz.getDeclaredMethod(name, parameterTypes);


            if (!method.isAccessible()) {
                method.setAccessible(true);
            }

            return method;
        } catch (NoSuchMethodException e) {
            // ignore and search next
        }
    }

    throw new NoSuchMethodException("Method " + name + " with parameters " +
            parameterTypes + " not found in " + instance.getClass());
}
 
Example 8
Project: boohee_v5.6   File: ViewUtils.java   View Source Code Vote up 6 votes
public static void makeOptionalFitsSystemWindows(View view) {
    if (VERSION.SDK_INT >= 16) {
        try {
            Method method = view.getClass().getMethod("makeOptionalFitsSystemWindows", new Class[0]);
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            method.invoke(view, new Object[0]);
        } catch (NoSuchMethodException e) {
            Log.d(TAG, "Could not find method makeOptionalFitsSystemWindows. Oh well...");
        } catch (InvocationTargetException e2) {
            Log.d(TAG, "Could not invoke makeOptionalFitsSystemWindows", e2);
        } catch (IllegalAccessException e3) {
            Log.d(TAG, "Could not invoke makeOptionalFitsSystemWindows", e3);
        }
    }
}
 
Example 9
Project: jaffa-framework   File: TransformerUtils.java   View Source Code Vote up 5 votes
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);
        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;
    }
}
 
Example 10
Project: util   File: ClassUtil.java   View Source Code Vote up 5 votes
/**
 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 */
public static void makeAccessible(Method method) {
	if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
			&& !method.isAccessible()) {
		method.setAccessible(true);
	}
}
 
Example 11
Project: marathonv5   File: AssertionTreeView.java   View Source Code Vote up 5 votes
private AssertionTreeItem getTreeItemForMethod(Object object, Method method) {
	boolean accessible = method.isAccessible();
	try {
		method.setAccessible(true);
		return new AssertionTreeItem(method.invoke(object, new Object[] {}), getPropertyName(method.getName()));
	} catch (Throwable t) {
	} finally {
		method.setAccessible(accessible);
	}
	return null;
}
 
Example 12
Project: comdor   File: DisconnectedTestCase.java   View Source Code Vote up 5 votes
/**
 * All the methods of Disconnect should throw ISE.
 * @throws Exception If something goes wrong.
 */
@Test
public void allMethodsThrowISE() throws Exception {
    for(final Method method : Disconnected.class.getDeclaredMethods()) {
        try {
            if(!method.isAccessible()) {
                continue;
            }
            Object[] params = new Object[method.getParameterCount()];
            for(int i=0; i < method.getParameters().length; i++) {
                if(method.getParameters()[i].getType().equals(int.class)) {
                    params[i] = 0;
                } else if(method.getParameters()[i].getType().equals(boolean.class)) {
                    params[i] = false;
                } else {
                    params[i] = null;   
                }
            }
            method.invoke(new Disconnected(), params);
            Assert.fail("ISE should have been thrown by now!");
        } catch (final InvocationTargetException ex) {
            MatcherAssert.assertThat(
                ex.getCause().getMessage(),
                Matchers.equalTo(
                    "Not connected. Don't forget to "
                    + "get a connected instance by calling #connect()"
                )
            );
        }
    }
}
 
Example 13
Project: gen_code   File: AnalysisObject.java   View Source Code Vote up 5 votes
/**
 * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
 * @param method 要设置的方法
 */
public static void makeAccessible(Method method) {
	if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
			&& !method.isAccessible()) {
		method.setAccessible(true);
	}
}
 
Example 14
Project: hadoop-oss   File: RetryInvocationHandler.java   View Source Code Vote up 5 votes
protected Object invokeMethod(Method method, Object[] args) throws Throwable {
  try {
    if (!method.isAccessible()) {
      method.setAccessible(true);
    }
    return method.invoke(currentProxy.proxy, args);
  } catch (InvocationTargetException e) {
    throw e.getCause();
  }
}
 
Example 15
Project: Hubs   File: JavaMethod.java   View Source Code Vote up 5 votes
private JavaMethod(Method m) {
	super( m.getParameterTypes(), m.getModifiers() );
	this.method = m;
	try {
		if (!m.isAccessible())
			m.setAccessible(true);
	} catch (SecurityException s) {
	}
}
 
Example 16
Project: promagent   File: Delegator.java   View Source Code Vote up 5 votes
private static void invoke(Class<? extends Annotation> annotation, Object hookInstance, Method interceptedMethod, Object[] args, Object returned, Throwable thrown) throws HookException {
    if (args.length != interceptedMethod.getParameterCount()) {
        throw new IllegalArgumentException("Number of provided arguments is " + args.length + ", but interceptedMethod expects " + interceptedMethod.getParameterCount() + " argument(s).");
    }
    for (Method method : findHookMethods(annotation, hookInstance.getClass(), interceptedMethod)) {
        try {
            if (!method.isAccessible()) {
                method.setAccessible(true);
            }
            method.invoke(hookInstance, addReturnedAndThrownArgs(method, args, returned, thrown));
        } catch (Exception e) {
            throw new HookException("Failed to call " + method.getName() + "() on " + hookInstance.getClass().getSimpleName() + ": " + e.getMessage(), e);
        }
    }
}
 
Example 17
Project: hadoop   File: RetryInvocationHandler.java   View Source Code Vote up 5 votes
protected Object invokeMethod(Method method, Object[] args) throws Throwable {
  try {
    if (!method.isAccessible()) {
      method.setAccessible(true);
    }
    return method.invoke(currentProxy.proxy, args);
  } catch (InvocationTargetException e) {
    throw e.getCause();
  }
}
 
Example 18
Project: NotifyTools   File: MethodUtils.java   View Source Code Vote up 4 votes
/**
 * Try to make the method accessible
 * @param method The source arguments
 */
private static void setMethodAccessible(final Method method) {
    try {
        //
        // XXX Default access superclass workaround
        //
        // When a public class has a default access superclass
        // with public methods, these methods are accessible.
        // Calling them from compiled code works fine.
        //
        // Unfortunately, using reflection to invoke these methods
        // seems to (wrongly) to prevent access even when the method
        // modifer is public.
        //
        // The following workaround solves the problem but will only
        // work from sufficiently privilages code.
        //
        // Better workarounds would be greatfully accepted.
        //
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }

    } catch (final SecurityException se) {
        // log but continue just in case the method.invoke works anyway
        final Log log = LogFactory.getLog(MethodUtils.class);
        if (!loggedAccessibleWarning) {
            boolean vulnerableJVM = false;
            try {
                final String specVersion = System.getProperty("java.specification.version");
                if (specVersion.charAt(0) == '1' &&
                        (specVersion.charAt(2) == '0' ||
                         specVersion.charAt(2) == '1' ||
                         specVersion.charAt(2) == '2' ||
                         specVersion.charAt(2) == '3')) {

                    vulnerableJVM = true;
                }
            } catch (final SecurityException e) {
                // don't know - so display warning
                vulnerableJVM = true;
            }
            if (vulnerableJVM) {
                log.warn(
                    "Current Security Manager restricts use of workarounds for reflection bugs "
                    + " in pre-1.4 JVMs.");
            }
            loggedAccessibleWarning = true;
        }
        log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se);
    }
}
 
Example 19
Project: DroidPlugin   File: ServcesManager.java   View Source Code Vote up 4 votes
private void handleCreateServiceOne(Context hostContext, Intent stubIntent, ServiceInfo info) throws Exception {
    //            CreateServiceData data = new CreateServiceData();
    //            data.token = fakeToken;// IBinder
    //            data.info =; //ServiceInfo
    //            data.compatInfo =; //CompatibilityInfo
    //            data.intent =; //Intent
    //            activityThread.handleCreateServiceOne(data);
    //            service = activityThread.mTokenServices.get(fakeToken);
    //            activityThread.mTokenServices.remove(fakeToken);
    ResolveInfo resolveInfo = hostContext.getPackageManager().resolveService(stubIntent, 0);
    ServiceInfo stubInfo = resolveInfo != null ? resolveInfo.serviceInfo : null;
    PluginManager.getInstance().reportMyProcessName(stubInfo.processName, info.processName, info.packageName);
    PluginProcessManager.preLoadApk(hostContext, info);
    Object activityThread = ActivityThreadCompat.currentActivityThread();
    IBinder fakeToken = new MyFakeIBinder();
    Class CreateServiceData = Class.forName(ActivityThreadCompat.activityThreadClass().getName() + "$CreateServiceData");
    Constructor init = CreateServiceData.getDeclaredConstructor();
    if (!init.isAccessible()) {
        init.setAccessible(true);
    }
    Object data = init.newInstance();

    FieldUtils.writeField(data, "token", fakeToken);
    FieldUtils.writeField(data, "info", info);
    if (VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB) {
        FieldUtils.writeField(data, "compatInfo", CompatibilityInfoCompat.DEFAULT_COMPATIBILITY_INFO());
    }

    Method method = activityThread.getClass().getDeclaredMethod("handleCreateService", CreateServiceData);
    if (!method.isAccessible()) {
        method.setAccessible(true);
    }
    method.invoke(activityThread, data);
    Object mService = FieldUtils.readField(activityThread, "mServices");
    Service service = (Service) MethodUtils.invokeMethod(mService, "get", fakeToken);
    MethodUtils.invokeMethod(mService, "remove", fakeToken);
    mTokenServices.put(fakeToken, service);
    mNameService.put(info.name, service);


    if (stubInfo != null) {
        PluginManager.getInstance().onServiceCreated(stubInfo, info);
    }
}
 
Example 20
Project: util   File: ReflectionUtils.java   View Source Code Vote up 3 votes
/**
 * Make the given method accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called when
 * actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).
 * 
 * @param method
 *            the method to make accessible
 * @see java.lang.reflect.Method#setAccessible
 */
public static void makeAccessible(Method method) {
	if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
			&& !method.isAccessible()) {
		method.setAccessible(true);
	}
}