tags:

views:

851

answers:

4

Is it possible to get the path to my .class file containing my main function from within main?

A: 

According to http://www.cs.caltech.edu/courses/cs11/material/java/donnie/java-main.html, no. However, I suggest reading http://stackoverflow.com/questions/41894/0-program-name-in-java-discover-main-class , which at least gives you the main class .

Brian
Within the `main` method, the enclosing class is already known.
erickson
+4  A: 
URL main = Main.class.getResource("Main.class");
if (!"file".equalsIgnoreCase(main.getProtocol()))
  throw new IllegalStateException("Main class is not stored in a file.");
File path = new File(main.getPath());

Note that most class files are assembled into JAR files so this won't work in every case (hence the IllegalStateException). However, you can locate the JAR that contains the class with this technique, and you can get the content of the class file by substituting a call to getResourceAsStream() in place of getResource(), and that will work whether the class is on the file system or in a JAR.

erickson
A: 

What do you need it for? If you need it to get hold of any files that are in the same directory, that's what Class.getResourceAsStream() is for.

Michael Borgwardt
trying to get a lock on my main class file in order to stop launching of my application more than once.
Hamza Yerlikaya
A: 

That looks more like an end-user issue to me. Also consider the possible need to run multiple instances of any given application, and preventing users from doing so is going to become a major annoyance.

If the problem is with temporary file conflicts, then just make sure all your temporary files have unique names. This, as I understand it, is the most common reason people feel a need to prevent multiple instances of their applications from running.

P.S.: The java.io.File.createTempFile() methods are ideally suited for preventing temporary file conflicts because they automatically generate unique filenames.

Randolf Richardson