How to make Class.getMethod () throw a SecurityException

I have a utility method for finding the getter method of an object for a specific 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 describes a SecurityException script, but how can I make getMethod throw a SecurityException?

getMethod will raise a SecurityException

If security manager s is present and any of the following conditions are true:

  • calling s.checkMemberAccess (this one, Member.PUBLIC) denies access to the method

  • the caller's classloader does not match the ancestor of the classloader for the current class and calling s.checkPackageAccess () denies access to the package of this class

I would rather throw an exception normally instead of resorting to a mocking structure.

+8
java reflection junit
source share
2 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 the finally block to restore it to its original state.

+11
source share

Regarding this in regular setup, there are very few cases where this can happen.

Non-public methods will result in a NoSuchMethodException because getMethod specifically searches only public methods. getDeclaredMethod will find this method, but will allow the return of private / protected methods.

The only real way to do this is, as javadocs say, to have a separate package that is protected by a security manager, which, I assume, can only be executed with unsigned applets or similar permissions. (I never came across this myself, so I'm not quite sure)

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

0
source share

All Articles