There is an optional attribute stored in the ".class" file that gives the filename (not pathname) for the source Java file. JVM spec 4.7.10.
The spec says:
"The string referenced by the sourcefile_index item will be interpreted as indicating the name of the source file from which this class file was compiled. It will not be interpreted as indicating the name of a directory containing the file or an absolute path name for the file; such platform-specific additional information must be supplied by the run-time interpreter or development tool at the time the file name is actually used."
This attribute is not exposed by java.lang.Class
, but if you can (somehow) arrange for an exception to be instantiated while a method of the class is on the stack, the source filename may be obtainable by calling StackTraceElement.getFileName()
... modulo the disclaimers in the javadoc.
Alternatively, if you can locate the class file, it should be possible to decode it and extract the source filename. (You should be able to find an existing library 3rd-party to do the decoding / extraction.)
HOWEVER:
- As stated above, what you get is a simple filename, not a pathname.
- The name is not necessarily a real filename. It could be the name of something in a repository / database that contains the source. (According to the javadoc disclaimers.)
- The attribute is optional which means that it may not be present at all.
All of that adds up to this: you probably should find another way to do whatever it is that you are trying to do.