简体   繁体   中英

How to make Class.getMethod() throw a SecurityException

I have a utility method to find an object's getter method for a particular field (using reflection):

public static Method findGetter(final Object object, final String fieldName) {
    if( object == null ) {
        throw new NullPointerException("object should not be null");
    } else if( fieldName == null ) {
        throw new NullPointerException("fieldName should not be null");
    }

    String getterName = getMethodNameForField(GET_PREFIX, fieldName);

    Class<?> clazz = object.getClass();
    try {
        return clazz.getMethod(getterName);
    } catch(final NoSuchMethodException e) {
        // exception handling omitted
    } catch(final SecurityException e) {
        // exception handling omitted
    }
}

I would like to write a unit test that covers the SecurityException scenario, but how can I make getMethod throw a SecurityException?

The javadoc states that getMethod will throw SecurityException

If a security manager, s, is present and any of the following conditions is met:

  • invocation of s.checkMemberAccess(this, Member.PUBLIC) denies access to the method

  • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

I would prefer to trigger the exception normally, rather than resorting to a mocking framework.

System.setSecurityManager(new SecurityManager(){
    @Override
    public void checkMemberAccess(Class<?> clazz, int which) {
        throw new SecurityException("Not allowed")
    }
    @Override
    public void checkPermission(Permission perm) {
        // allow resetting the SM
    }
});
ClassTest.class.getMethod("foo");

Remember to call System.setSecurityManager(null) in a finally block to restore the original state.

As far as causing this in a regular setting, there are very little cases where this can happen.

Non-public methods will result in a NoSuchMethodException , because getMethod specifically looks for public methods only. getDeclaredMethod will find the method, but allows private/protected methods to be returned.

The only real way to do this is to, as the javadocs say, have a separate package that is protected by the security manager, which I'm guessing can only be done with unsigned applets or similar permissions. (I have never run into this myself, so I am not entirely sure)

Your best bet is forcing the exception to be thrown for specific methods by overriding the security manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM