在阅读和扫描旧代码时,我看到了这些代码行:
public static void replaceNull(Object obj)
{
if (obj == null)
{
return;
}
Field[] fields = obj.getClass().getDeclaredFields();
if (fields != null)
{
for (Field field : fields)
{
field.setAccessible(true);
Class<?> fieldType = field.getType();
try
{
if (field.get(obj) == null)
{
setDefaultValue(obj, field, fieldType);
}
} catch (IllegalArgumentException e)
{
logger. error("failed replacing null :"+ e.getMessage(),e);
} catch (IllegalAccessException e)
{
logger. error("failed replacing null :"+ e.getMessage(),e);
}
}
}
}
private static void setDefaultValue(Object obj, Field field, Class<?> fieldType) throws IllegalAccessException
{
if (fieldType == String.class)
{
field.set(obj, CommonConstants.BLANK);
} else if (fieldType == Date.class)
{
field.set(obj, new Date());
} else if (fieldType == Long.class)
{
field.setLong(obj, 0L);
} else if (fieldType == Integer.class)
{
field.setInt(obj, 0);
} else if (fieldType == BigDecimal.class)
{
field.set(obj, new BigDecimal("0.0"));
}
}
从程序流程来看,编写者似乎想为对象的所有数据成员创建一个默认值,如果值为空的话。
使用 FindBugs 扫描后,findbugs 报告了“DP_DO_INSIDE_DO_PRIVILEGED”,并在 setAccessible(true) 上进行了描述:
Bad practice - Method invoked that should be only be invoked inside a doPrivileged block Plugin: findbugs Key: DP_DO_INSIDE_DO_PRIVILEGED This code invokes a method that requires a security permission check. If this code will be granted security permissions, but might be invoked by code that does not have security permissions, then the invocation needs to occur inside a doPrivileged block.
我的问题是为什么这么糟糕?又该如何解决?
最佳答案
来自 field#setAccessible(boolean)
的 Javadocs :
First, if there is a security manager, its checkPermission method is called with a ReflectPermission("suppressAccessChecks") permission.
没有 SecurityManager
安装,程序将运行良好。但是,假设您的代码是作为一个共享库编写的,它恰好被一些已经设置了安全管理器的模块使用。在这种情况下,field.setAccessible(true)
即使您的代码中的此操作和其他操作被视为可信代码,也可能会被拒绝许可。这就是 FindBugs 发出此警告的原因。
为了保证field.setAccessible(true)
无论调用者代码的权限如何,都将始终被授予权限,您可以将语句包装在 AccessController.doPrivileged
中(你必须使 field
最终):
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Object run() {
field.setAccessible(true);
return null;
}
});
关于java - 如何解决FindBugs DP_DO_INSIDE_DO_PRIVILEGED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14278870/