Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This compliant solution invokes a security manager check as a side-effect of computing the boolean value passed to a private constructor (as seen in guideline OBJ04-J. Do not allow access to partially initialized objects). The rules for order of evaluation require that the security manager check must execute before invocation of the private constructor. Consequently, the security manager check also executes before invocation of any superclass's constructor. Note that the security manager check is made without regard to whether the object under construction has the type of the parent class or the type of a subclass (whether trusted or not).

Wiki Markup
This solution thwarts the finalizer attack. It is specific to Java SE 6 and onwards, where a finalizer is prevented from being executed when an exception is thrown before the {{java.lang.Object}} constructor exits \[[SCG 2009|AA. Bibliography#SCG 09]\].

Code Block
bgColor#ccccff
public class NonFinal {
  public NonFinal() {
    this( check( this.getClass())); // throws a security exception if not allowed
  }
  
  private NonFinal(boolean securityManagerCheck) {
    // regular construction goes here
  }

  private static boolean check(Class c) {
    // Confirm class type
    if (c != NonFinal.class) {
      // Check the permission needed to subclass NonFinal
      securityManagerCheck(); // throws a security exception if not allowed
    }

    return true;
  }
}

...

Wiki Markup
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 1: "Consider static factory methods instead of constructors"
\[[Gong 2003|AA. Bibliography#Gong 03]\] Chapter 6: "Enforcing Security Policy"
\[[Lai 2008|AA. Bibliography#Lai 08]\]
\[[McGraw 2000|AA. Bibliography#McGraw 00]\] Chapter Seven Rule 3: "Make Everything Final, Unless There's a Good Reason Not To"\[[SCG 2007|AA. Bibliography#SCG 07]\] Guideline 1-2 "Limit the extensibility of classes and methods"
\[[SCG 2009|AA. Bibliography#SCG 09]\]

...

OBJ04-J. Do not allow access to partially initialized objects      04. Object Orientation (OBJ)      OBJ06-J. Compare classes and not class names