views:

92

answers:

3

Hi,

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.

+2  A: 

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.

Tenner
+3  A: 

No you can't. Its a little illogical as well.

cx0der
+3  A: 

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

Atmocreations
Actualy I'm writing Scala code :). I formulated the question as a Java one because I think it's a more general question. My use-case it's a method which gets some function as a parameter and I want to get, inside the method, the "text" of the actual function for reporting needs.
german1981
well... if you have the source-code you could try to parse it yourself. I think a well-defined regex could get you a method's body. But you would need to decompile it using javad for example... you could do it with a script or with some java/scala code...
Atmocreations
I think I will go this way. I'll post here the results. Thanks.
german1981