简体   繁体   中英

In Java, how to get the Abstract Syntax Tree from class files?

As we know, we can get the abstract syntax tree from the source codes, using the tool like

org.eclipse.jdt.astview

But given the compiled class files, how to get the ASTs? Is there any existing tools? Can soot do it?

Thanks!

But given the compiled class files, how to get the ASTs?

You can't. It is not technically possible to reconstruct an AST for the original source code from a ".class" file. A lot of the information needed is no longer present in any form, and other information has been transformed irreversibly.

Is there any existing tools?

No.

The standard "answer" is to use a decompiler but:

  • a decompiler cannot reconstruct the original AST (see above)
  • the output of a decompiler often doesn't even remotely resemble the original source code
  • often the decompiled code won't even compile.

Decompile and do the same thing.

Bytecode has no S, bytecode is the result of an AST-to-bytecode transformation.

How about for a given classfile, we first decompile it using tool like jad , then we could get the "source code".

Even though this "source code" from decompilation is not exactly the same with the original one, it shares the same semantics. Below is a simple test.

Original java file:

package shape.circle;
public class Circle
{   int r;  // this is radius of a circle
    public Circle(int r)
    {   this.r = r;
    }

    /* get the diameter
       of this circle
    */
    public int getDiameter()
    {
        if(r==0)
        {   System.out.println("r is 0");
            return -1;
        }
        else
        {   int d = multiply(2,r);
            return d;
        }
    }

    int multiply(int a, int b)
    {   int c;
        c = a * b;
        return c;
    }
}

Below is the decompiled java file from Circle.class .

package shape.circle;
import java.io.PrintStream;
public class Circle
{

    public Circle(int i)
    {  r = i;
    }

    public int getDiameter()
    {   if(r == 0)
        {   System.out.println("r is 0");
            return -1;
        } else
        {
            int i = multiply(2, r);
            return i;
        }
    }

    int multiply(int i, int j)
    {
        int k = i * j;
        return k;
    }

    int r;
}

They are almost the same. Then as before, we can use the tool for source code

org.eclipse.jdt.astview

to get the AST.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM