开发者

What are the java equivalents of python's __file__, __name__, and Object.__class__.__name__?

In Python you can get the path of the file that is executing via __file__ is there a java equivalent?

Also is there a way to get the current package you are in similar to __name__?

And Lastly, What is a good resource for java i开发者_开发百科ntrospection?


this.getClass() = current class
this.getClass().getPackage() = current package
Class.getName() = string of class name
Package.getName() = string of package name

I believe you're looking for the Reflection API to get the equivalent of introspection (http://download.oracle.com/javase/tutorial/reflect/).


@Christopher's answer addresses the issue of the class name.

AFAIK, the standard Java class library provides no direct way to get hold of the filename for an object's class.

If the class was compiled with the appropriate "-g" option setting, you can potentially get the classes filename indirectly as follows:

  • Create an exception object in one of the classes methods.
  • Get the exception's stack trace information using Throwable.getStackTrace().
  • Fetch the stacktrace element for the current method, and use StackTraceElement.getFilename() to fetch the source filename.

Note this is potentially expensive, and there is no guarantee that a filename will be returned, or that it will be what you expect it to be.


You can get the folder (excluding packages) containing the class file:

SomeClass.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();


You can use the reflection to navigate the stacktrace:

new Throwable().getStackTrace()[1].getFileName()
new Throwable().getStackTrace()[1].getClassName()
new Throwable().getStackTrace()[1].getMethodName()
new Throwable().getStackTrace()[1].getLineNumber()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜