Friday, June 10, 2011

Twelve rules for developing more secure Java code-Rule 5


Rule 5: Don't use inner classes

Some Java language books say inner classes can be accessed only by the outer classes that enclose them. But this isn't true. Java bytecode has no concept of inner classes, so inner classes are translated by the compiler into ordinary classes that happen to be accessible to any code in the same package. And Rule 4 says not to depend on package scope for protection. 

But wait, it gets worse. An inner class gets access to the fields of the enclosing outer class, even if the these fields are declared private. And the inner class is translated into a separate class. To let this separate class access the fields of the outer class, the compiler silently changes these fields from private to package scope! It's bad enough that the inner class is exposed; but it's even worse that the compiler is silently overruling your decision to make some fields private. Don't use inner classes if you can help it. (Ironically, the new JDK 1.2 PrivilegedAction API requires you to use an inner class to write privileged code. For more details, see our book Securing Java and the developer.com article referenced below.) That's one reason we don't like the PrivilegedAction API.)

No comments: