Monday, November 1, 2010

Limit the accessibility of classes,interfaces, methods, and fields in Java

Limit the accessibility of classes,interfaces, methods, and fields

A Java package comprises a grouping of related Java classes and interfaces. Declare any class or interface public if it is specified as part of a published application programming interface (API). Otherwise, declare it package-private. Likewise, declare class members and constructors (nested classes, methods, or fields) public or protected as appropriate, if they are also part of the API. Otherwise, declare them private or package-private to avoid exposing implementation. Note that members of interfaces are implicitly public.

Classes loaded by different loaders, although they may have the same package name, do not have package-private access to one another. Classes in the same package loaded by the same class loader must either share the same code signing certificate or not have a certificate at all. In the Java virtual machine, class loaders are responsible for defining packages. It is recommended that as a matter of course, packages are marked as sealed in the jar file manifest.

Limit the accessibility of packages

Containers may hide implementation code by adding to the package.access security property. This property prevents untrusted classes from other class loader linking and using reflection on the specified package hierarchy. Care must be taken to ensure that packages cannot be accessed by untrusted contexts before this property has been set.

This example code demonstrates how to append to the package.access security property. Note that it is not thread-safe. This code should generally only appear once in a system.

private static final String PACKAGE_ACCESS_KEY = "package.access";
    static {
        String packageAccess = java.security.Security.getProperty(
            PACKAGE_ACCESS_KEY
        );
        java.security.Security.setProperty(
            PACKAGE_ACCESS_KEY,
            (
                (packageAccess == null || packageAccess.trim().isEmpty()) ?
                "" :
                (packageAccess + ",")
            ) +
            "xx.example.product.implementation."
        );
    }

No comments:

Post a Comment