Skip to content

Latest commit

 

History

History
42 lines (34 loc) · 1.49 KB

AvoidAccessibilityAlteration.md

File metadata and controls

42 lines (34 loc) · 1.49 KB

AvoidAccessibilityAlteration

Category: pmd
Rule Key: pmd:AvoidAccessibilityAlteration


Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation.

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();

} }