Thursday, August 15, 2013

What's in .Class file - Contd.

This is continuation of post. Now, we will see bit in detail with an example
package com.test;
public class Employee
{
     .....
     public void setEmpid(int empid)
     {
          this.empid = empid;
     }
     ....    
     public double getSalary()
     {
          return salary;
     }
     public void setSalary(double salary)
     {
          this.salary = salary;
     }
}
For example, take the above block's byte code one by one
public void setEmpid(int);
  Code:
   0:   aload_0
   1:   iload_1
   2:   putfield        #2; //Field empid:I
   5:   return
The code is pretty readable. load means loading a value. Each load is prefixed by a character ( 'i' means integer, 'd' means decimal and 'a' means an object. putfield means setting a value to other variable. Each function will have a return statement at the end. If the function has a void return type, then simple return otherwise return will be prefixed by a character. For example getSalary() method as below
public double getSalary();
  Code:
   0:   aload_0
   1:   getfield        #4; //Field salary:D
   4:   dreturn
Each and every line in the java byte code is called opcode as we discussed has a special meaning. We can find the list of all opcodes in the JVM Spec or on Wiki. Apart from the load, put, get, return, new (That we saw). There are method invocations which you will find more common. These start with invoke prefix
  • invokespecial: Used to call the instance private as well as public method (including initializations)
  • invokevirtual : Used to call a method based on the class of the object. 
  • invokestatic : Invokes a static method. 
  • so on....
Will post some more details in the next posts.

No comments:

Post a Comment