user2280250
user2280250

Reputation: 41

How get method body offset from Java .class file

How find on a Java .class file where start the method body

Ex.

package com.test;

class Hello
{

    public static boolean isTrue()  {
        return true;
    }

    public static void main(String args[])
    {

    }
}

I want know where start isTrue() method body on Hello.class

I can find 04 0C (bytecode: iconst_1 ireturn ) with a hexeditor at address 0x0205 but I want this value programmatically for any method by name.

Upvotes: 2

Views: 802

Answers (1)

Antimony
Antimony

Reputation: 39451

In the JVM classfile format, offsets aren't stored to particular sections. Instead, each item has its own length, and it is parsed sequentially. This means that in order to find the method code, you'll at the very least have to be able to parse the constant pool to get each type and calculate string lengths, as methods come after the constant pool.

At that point you might as well use a fully featured classfile parser. There are quite a few libraries out there.

P.S. At the bytecode level, methods are not identified uniquely by name, but by (name, descriptor) pairs. Multiple methods can have the same name. The same goes for fields.

Upvotes: 1

Related Questions