resources.report.rules.pmd.AvoidAccessibilityAlteration.html Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sanity4j Show documentation
Show all versions of sanity4j Show documentation
Sanity4J was created to simplify running multiple static code
analysis tools on the Java projects. It provides a single entry
point to run all the selected tools and produce a consolidated
report, which presents all findings in an easily accessible
manner.
The newest version!
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();
}
}