
resources.report.rules.pmd.AvoidAccessibilityAlteration.html Maven / Gradle / Ivy
AvoidAccessibilityAlteration
AvoidAccessibilityAlteration
Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(),
as the interface PrivilegedAction, allow to alter, at runtime, the visilibilty of variable, classes, or
methods, even if they are private. Obviously, no one should do so, as such behavior is against everything
encapsulation principal stands for.
This rule is defined by the following XPath expression:
//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:
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();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy