How to do OO on a stack machine.

I’m no expert on the Java internals, nor do I do any kind of language design. I do find some of the lower level internals of the Java language runtime very interesting. Take a simple class with implementation and visibility modifiers omitted.


public class Foo {
static int j = 0;
Foo()
Foo(Foo aFoo)
int getI()
void setI(int i)
static void somethingStatic()
}

When this class is compiled to byte code it becomes semantically closer to this.


public class Foo {
<clinit>()
LFoo <init>()
LFoo <init>(LFoo)
I getI(LFoo)
V setI(LFoo, I)
V somethingStatic()
}

There are two new method names here that we didn’t specify <clinit> and <init> there are initialization methods that are written into the class by the compiler. <init> is a method that returns a new instance of the object AKA. constructor. <clinit> is the static initializer, it sets j to 0, and would perform any other static initialization logic.

A few other quick notes:

  • L in LFoo means that we are dealing in language references.
  • I means primitive integer.
  • V is void return type.

You will also notice that any distinction between instance and static invocation had disappeared. Really isn’t expressed declarative at the byte code level. All instance methods assume that their first parameter will be the reference to their instance, whereas static methods are invoked without a parameter reference to their instance. Note, the instance reference is not an actual part of the method descriptor as I indicated above, it is simply implied. All distinction between static and nonstatic is at invocation, by using the appropriate bytecode instruction:

  • invokeinterface - Invoke interface method
  • invokespecial - Invoke instance method; special handling for superclass, private, and instance initialization method invocations
  • invokestatic - Invoke a class (static) method
  • invokevirtual - Invoke instance method; dispatch based on class

The beauty at the byte code level is its simplicity. There is no magic, to me it just makes sense, and if you didn’t know before now you know what it means when you see a <clinit> or a <init> in a stack trace..

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • del.icio.us
  • Facebook
  • Reddit
  • StumbleUpon

Tags:

Leave a Reply