如何使Class.getMethod()抛出SecurityException

Jam*_*ett 8 java reflection junit

我有一个实用工具方法来查找特定字段的对象的getter方法(使用反射):

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我想编写一个涵盖SecurityException场景的单元测试,但是如何让getMethod抛出SecurityException呢?

javadoc声明getMethod将抛出SecurityException

如果存在安全管理器s,并且满足以下任何条件:

  • 调用s.checkMemberAccess(this,Member.PUBLIC)拒绝访问该方法

  • 调用者的类加载器与当前类的类加载器的祖先或祖先不同,并且调用s.checkPackageAccess()拒绝访问此类的包

我宁愿通常触发异常,而不是诉诸于模拟框架.

Boz*_*zho 11

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");
Run Code Online (Sandbox Code Playgroud)

记得System.setSecurityManager(null)finally块中调用以恢复原始状态.