开发者

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

开发者 https://www.devze.com 2022-12-08 05:24 出处:网络
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 ans

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 whic开发者_高级运维h 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.


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消