Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
James Bassett Avatar asked Feb 20 '12 20:02

James Bassett


1 Answers

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.

like image 130
Bozho Avatar answered Sep 28 '22 20:09

Bozho