Getting Java source code from a class name

Is there a way to get Java source code from a class name?

For example, if I have access to a library with a class java.io.File, I want its source code.

I am working on some kind of parser and I need a source at runtime. I also have to look for it recursively.

Say the above class has this method:

int method (User user) {...}

I would need to get the source code User, etc. etc. with their inner classes.

+3
source share
7 answers

Is there any way to get java source from class name? For instance:...

, . , , , , , . JSE , , . , , , , , .

, API Java Reflection API. , , , , , .....

Class clazz = User.class;
Field field = clazz.getDeclaredField("var");
System.out.println(field.getType().getName());

, , , -.

, ( ) Class.forName("MyClass") .

, -. , - , - API - . ASM.

, , , ... , . ASM .

, , , . , , [] . , . Jode, - .

, , , , .java - .

Class clazz = User.class;
String path = clazz.getPackage().getName().replaceAll("\\.","/");
File sourceFile = new File(path, clazz.getName() + ".java")

, , , primatives , -.

( .class ) Class.forName("MyClass").

+6

JAVA , , java.io.File, .

+3

javap

hello.java

public class hello
{
    public static void main(String[] args)
    {
    System.out.println("hello world!");
    world();
    }

    static public void world()
    {
    System.out.println("I am second method");
    }
}

a javap hello, :

Compiled from "hello.java"
public class hello extends java.lang.Object{
    public hello();
    public static void main(java.lang.String[]);
    public static void world();
}
+3

, . .

Eclipse , , > ( s > F3), .

+2

, , Java-. Java.

0

- , , API Java . , , , .. , .

0

java ?

, - . (, ).

  • , Java .

  • () ZIP JAR , , . ZIP/JAR - .

  • , .., API Java. , (. -g javac), . , .

  • -. , .

  • I assume that if you have the URL of a site filled with javadocs for classes, you can go from the class name, method name, or public attribute name to the corresponding javadoc URL at runtime. You could even “clear the screen” of descriptions from javadocs. But again, this is not real source code.

0
source

Source: https://habr.com/ru/post/1753420/


All Articles