tags:

views:

102

answers:

3

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 introspection?

+7  A: 

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 W. Allen-Poole
+4  A: 

@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.

Stephen C
I can't cite my source for this, but I do recall reading somewhere that if you decide to do something like that (and PLEASE keep it out of production level code), you can speed it up by using native exceptions (such as NullPointerException) instead of simply constructing your own because native exceptions are already cached(? speculation on the original author's part). IE: try{ Object o; o.toString(); }catch( NullPointerException e ){} is faster than try{ throw new Exception( "foo" ) }catch( Exception e ){}
Christopher W. Allen-Poole
That won't work. The exception needs to be instantiated in the normal way to allow you to capture the stacktrace information for the current context. Whether you simply construct it or do something to make the JVM construct it makes little difference. (In fact I suspect that the latter would actually be slower because the exception has to be thrown and caught as well.)
Stephen C
+1  A: 

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

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