Why is the constant pool (in Java classfile) indexed from 1 (and not 0)? What is the constant_pool[0] entry reserved for?

Curious Learner :

From the JVM specs (Chapter 4.1 "The ClassFile structure"), it is stated that "The constant_pool table is indexed from 1 to constant_pool_count - 1."

I'm curious why they're skipping [0] and what is this entry reserved for.

Antimony :

They skipped index 0 so that it can be used for cases where you would normally reference a constant pool entry, but instead want to indicate "nothing". It is the constant pool equivalent of a null pointer.

The most notable use for index 0 is for "catch all" exception handlers. An exception handler can either point to the constant pool entry for the class of exceptions it wants to handle, or just use index 0 to catch everything (this is equivalent to catching java/lang/Throwable). In practice, the compiler will generate catch all exception handlers to implement finally, synchronized blocks, and the cleanup portions of try with resources, among other things.

Other uses for index 0 include:

  • The superclass of java/lang/Object
  • The name of a parameter with no name
  • The outer class for classes which are not the member of another class (i.e. top level classes, local classes, and anonymous classes)
  • The inner name of anonymous classes
  • The enclosing method for classes which are not immediately enclosed in a method
  • Version info for a module with no version info
  • Dependencies for a module with no dependency info

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121633&siteId=1
Recommended