Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It's possible in Java to access the source code of a method "reflectively"?

I'm afraid that the answer is no, but maybe one of you surprises me.

Thanks.

Edit 1: I'm aware that the question doesn't make much sense but I think the point was understood and, sadly, the answer is no. Anyway I changed the title of the question adding quotes to the word "reflectively" and I will try to better explain my intentions just in case.

I have a instance of a type which is a subclass of some abstract type which has some known methods. I want to get, at runtime, a String with the source code of the actual implementation of one of such methods in the instance type.

I think it's worth pointing out that the actual type of the instance may be an anonimous inner class.... Also that a "decompiled" version of the source code it's good enough. The method I want to get the source, most of the time, has only one line....

Thanks.

like image 975
gerferra Avatar asked Oct 13 '09 21:10

gerferra


2 Answers

As other's pointed out: no.

You can access objects of a class, its methods etc. the way the JVM can. This is only possible because every class stores information about itself and its members when being compiled.

If I had to guess, this happens in Object, the rootobject in the inheritance tree. You may decompile the class file using a decompiler and use that one for examination. But you cannot access the sourcecode like a String or anything similar.

Think about it: If you have scala-code compiled for JVM, you cannot get the scala-code back either. And you cannot get java-code.

Is there any special reason you want to do this? May there be any other way you could try to achieve your goal, whatever it might be?

regards

like image 74
Atmocreations Avatar answered Oct 10 '22 00:10

Atmocreations


I don't think so. When the .java is compiled it becomes a .class; as far as I know Java doesn't have a built-in decompiler to turn that .class back into a .java. All that a runnable application knows about is .class files.

like image 35
James Cronen Avatar answered Oct 10 '22 00:10

James Cronen