The Inner Class Role

Assertion

The Virtual Machine bluntly ignores the inner class statute of a class. The binary class file does not distinguish between usages of the inner class and usages of the non-inner class.

Proof

Create the following files.

File inner/A.java

public class A {
  public static class B {
    public static String name() { return "Inner class"; }
  }
}

File non-inner/A$B.java

public class A$B {
  public static String name() { return "Non-inner class"; }
}

File C.java

public class C {
  public static void main(String[] args) {
    System.out.println(A.B.name());
  }
}

File D.java

public class D {
  public static void main(String[] args) {
    System.out.println(A$B.name());
  }
}

Compile class A, and package it in a JAR.

cd inner
javac A.java
jar cvf ../inner-class.jar *.class
cd ..

Compile class A$B and package it in a JAR.

cd non-inner
javac A.java
jar cvf ../non-inner-class.jar *.class
cd ..

Compile the first client class, using the JAR containing the inner class.

javac -classpath inner-class.jar C.java

Compile the second client class, using the JAR containing the non-inner class.

javac -classpath non-inner-class.jar D.java

Run the first client class, using the version of the JAR containing the non-inner class. (If you’re on a Windows-based computer, replace the colon with a semicolon.)

java -classpath .:non-inner-class.jar C

Run the second client class, using the version of the JAR containing the inner class. (If you’re on a Windows-based computer, replace the colon with a semicolon.)

java -classpath .:inner-class.jar D

The first client should fail to produce a result, because there is no inner class A.B in its classpath. Similarly, client D should fail to run, because there is no non-inner class A$B in its classpath. Both clients run successfully, printing out Non-inner class and Inner class, respectively. Quod erat demonstrandum.

Conclusion

The inner classes specification creates classes using a legal identifier character, the dollar sign, classes that can be replaced safely with non-inner class counterparts, in effect creating a security hazard.

Post a Comment

Your email is never published nor shared. Required fields are marked *