Can Java read it's own source code?
Possibly by using reflection.. or something.

I would like to dynamically display the code to each method inside of my interface. Any idea how that could be acheived?

Thank you.

Recommended Answers

All 2 Replies

Reflection is used for a class to examine its own (or another class's) behavior at runtime. For example, while the program was running, you could determine what methods the class has and invoke those methods.

You can find the source code file by figuring out the class name and locating the file with the name "classname.java". You can probably use getResource to find the .java file, although it can be complicated. If, for some reason, you do not know the class name (which you probably should know in advance) you can use the printClassName() example found at the top of the Class documentation.

If you know the String name of the class (like MyClass.java and you have the String "MyClass") then you can use the Class method "forName" to get a Class Object for it. Again, look at the documentation link I sent you on that.

To get the source code the easiest way is what I mentioned above - figure out the name of the class, which you probably know in advance, append ".java" to it using String concatenation, then open the .java file for reading, read in the contents, and display them somehow.

commented: Nice +20

Man you're awesome.
That's the second question of mine you've answered.
Fantastic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.