Java Code Examples for java.lang.reflect.Method#canAccess()

The following examples show how to use java.lang.reflect.Method#canAccess() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private static boolean canAccess(Method m, Object target) {
    // JDK9+ use j.l.r.AccessibleObject::canAccess, which respects module rules
    try {
        return (boolean) m.canAccess(target);
    } catch (Throwable t) {
        throw Util.sneakyThrow(t);
    }

}
 
Example 2
/**
 * null object parameter  for static members
 */
public void testStaticMember() throws Exception {
    Method m = Unsafe.class.getDeclaredMethod("throwIllegalAccessError");
    assertFalse(m.canAccess(null));
    assertTrue(m.trySetAccessible());

    try {
        // non-null object parameter
        m.canAccess(INSTANCE);
        assertTrue(false);
    } catch (IllegalArgumentException expected) { }
}
 
Example 3
/**
 * the specified object must be an instance of the declaring class
 * for instance members
 */
public void testInstanceMethod() throws Exception {
    Method m = Unsafe.class.getDeclaredMethod("addressSize0");
    assertFalse(m.canAccess(INSTANCE));

    try {
        m.canAccess(null);
        assertTrue(false);
    } catch (IllegalArgumentException expected) { }
}
 
Example 4
/**
 * the specified object must be an instance of the declaring class
 * for instance members
 */
public void testInvalidInstanceObject() throws Exception {
    Class<?> clazz = Class.forName("sun.security.x509.X500Name");
    Method m = clazz.getDeclaredMethod("size");

    try {
        m.canAccess(INSTANCE);
        assertTrue(false);
    } catch (IllegalArgumentException expected) { }
}