Search code examples
javasemanticsinstanceofboolean-expression

What type of object is the ReferenceType in an instanceof RelationalExpression?


In practice, Java expects an object for an input and output for much of its semantics, whether it be primitive types or actual objects, excluding such class metadata as type names, argument lists, and return types

Being inherently an OOP language, everything is treated as an object on an abstract level, whether or not everything is stored as an object in memory

So, I was wondering, what sort of object is the ReferenceType in the production, RelationalExpression (instanceof)?

For example, in the following expression:

object instanceof ReferenceType

I want to know if ReferenceType is an actual object or not, and if not, how is it represented by the JVM according to the JVM specification as bytecode and how does it function?


Solution

  • The ReferenceType is a symbolic reference. instanceof has a corresponding instanceof indexbyte1 indexbyte2 instruction according to the Java Virtual Machine Specification (Java 10). The two index bytes can be constructed into a 32-bit (unsigned) integer that is an index to the current class's runtime constant pool.

    The objectref, which must be of type reference, is popped from the operand stack. The unsigned indexbyte1 and indexbyte2 are used to construct an index into the run-time constant pool of the current class (§2.6), where the value of the index is (indexbyte1 << 8) | indexbyte2. The run-time constant pool item at the index must be a symbolic reference to a class, array, or interface type.

    Where the objectref is the left-hand object reference in an instanceof expression.

    The symbolic reference is resolved if the objectref is not null, and the objectref's type is evaluated against the resolved type to determine if objectref is an instance of ReferenceType:

    If objectref is null, the instanceof instruction pushes an int result of 0 as an int onto the operand stack.

    Otherwise, the named class, array, or interface type is resolved (§5.4.3.1). If objectref is an instance of the resolved class or array type, or implements the resolved interface, the instanceof instruction pushes an int result of 1 as an int onto the operand stack; otherwise, it pushes an int result of 0.