resources.report.rules.pmd.AvoidAccessibilityAlteration.html Maven / Gradle / Ivy
AvoidAccessibilityAlteration
AvoidAccessibilityAlteration
Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allows for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation.
//PrimaryExpression[
(
(PrimarySuffix[
ends-with(@Image,'getDeclaredConstructors')
or
ends-with(@Image,'getDeclaredConstructor')
or
ends-with(@Image,'setAccessible')
])
or
(PrimaryPrefix/Name[
ends-with(@Image,'getDeclaredConstructor')
or
ends-with(@Image,'getDeclaredConstructors')
or
starts-with(@Image,'AccessibleObject.setAccessible')
])
)
and
(//ImportDeclaration/Name[
contains(@Image,'java.security.PrivilegedAction')])
]
Example(s):
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Method;
import java.security.PrivilegedAction;
public class Violation {
public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
// Possible call to forbidden getDeclaredConstructors
Class[] arrayOfClass = new Class[1];
this.getClass().getDeclaredConstructors();
this.getClass().getDeclaredConstructor(arrayOfClass);
Class clazz = this.getClass();
clazz.getDeclaredConstructor(arrayOfClass);
clazz.getDeclaredConstructors();
// Possible call to forbidden setAccessible
clazz.getMethod("", arrayOfClass).setAccessible(false);
AccessibleObject.setAccessible(null, false);
Method.setAccessible(null, false);
Method[] methodsArray = clazz.getMethods();
int nbMethod;
for ( nbMethod = 0; nbMethod < methodsArray.length; nbMethod++ ) {
methodsArray[nbMethod].setAccessible(false);
}
// Possible call to forbidden PrivilegedAction
PrivilegedAction priv = (PrivilegedAction) new Object(); priv.run();
}
}