Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve FindBugs DP_DO_INSIDE_DO_PRIVILEGED

Tags:

java

findbugs

When reading and scanning an old codes, I saw these lines of code :

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

From the flow of the program, it seems that the writer want to create a default values for all of the data member of the object if the value is null.

Upon scanning using FindBugs, the findbugs reported "DP_DO_INSIDE_DO_PRIVILEGED" with this description on 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.

My question why is this bad? And how should I solve it?

like image 385
Rudy Avatar asked Jan 11 '13 13:01

Rudy


1 Answers

Adding to the accepted answer above, Using Java 1.7+ lambda expressions, the same can be achieved with:

AccessController.doPrivileged((PrivilegedAction) () -> {
    field.setAccessible(true);
    return null;
});
like image 59
VanagaS Avatar answered Nov 28 '22 06:11

VanagaS