Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 326
NorthIsUp Avatar asked Oct 25 '10 22:10

NorthIsUp


People also ask

What is the Python equivalent to a Java .jar file?

Python doesn't have any exact equivalent to a . jar file.

What is __ class __ in Python?

__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .


3 Answers

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/).

like image 142
cwallenpoole Avatar answered Oct 21 '22 05:10

cwallenpoole


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

like image 36
Stephen C Avatar answered Oct 21 '22 05:10

Stephen C


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

SomeClass.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
like image 3
Matt Wonlaw Avatar answered Oct 21 '22 06:10

Matt Wonlaw