gpt4 book ai didi

java - 如何使 Class.getMethod() 抛出 SecurityException

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:42:17 27 4
gpt4 key购买 nike

我有一个实用方法可以为特定字段查找对象的 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
}
}

我想编写一个涵盖 SecurityException 的单元测试场景,但我怎样才能制作getMethod抛出 SecurityException?

javadoc 声明 getMethod 将抛出 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

我更愿意正常触发异常,而不是求助于模拟框架。

最佳答案

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");

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

关于java - 如何使 Class.getMethod() 抛出 SecurityException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9368059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com