JVM Knowledge

The ConstantValue attribute is a fixed-length attribute in the attributes table of a field_info structure (§4.5). A ConstantValue attribute represents the value of a constant expression (JLS §15.28), and is used as follows:

  • If the ACC_STATIC flag in the access_flags item of the field_info structure is set, then the field represented by the field_info structure is assigned the value represented by its ConstantValue attribute as part of the initialization of the class or interface declaring the field (§5.5). This occurs prior to the invocation of the class or interface initialization method of that class or interface (§2.9.2).
  • Otherwise, the Java Virtual Machine must silently ignore the attribute.

There may be at most one ConstantValue attribute in the attributes table of a field_info structure.

The ConstantValue attribute has the following format:

ConstantValue_attribute {
    u2 attribute_name_index;
    u4 attribute_length;
    u2 constantvalue_index;
}

The items of the ConstantValue_attribute structure are as follows:

  • attribute_name_index

    The value of the attribute_name_index item must be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Utf8_info structure (§4.4.7) representing the string "ConstantValue".

  • attribute_length

    The value of the attribute_length item must be two.

  • constantvalue_index

    The value of the constantvalue_index item must be a valid index into the constant_pool table. The constant_pool entry at that index gives the value represented by this attribute. The constant_pool entry must be of a type appropriate to the field, as specified in Table 4.7.2-A.

    Table 4.7.2-A. Constant value attribute types

    Field Type Entry Type
    int, short, char, byte, boolean CONSTANT_Integer
    float CONSTANT_Float
    long CONSTANT_Long
    double CONSTANT_Double
    String CONSTANT_String