Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is there a way to obtain the command line parameters even if main() didn't save them?

We have a program with a main() that parses certain CLPs but does not save them anywhere. I then have my own plug-in code that needs access to the original CLPs (so I can transmit more parameters) for it. However, I cannot change main()

I saw that there is apparently a way to do this in C#, I'm looking for an equivalent Java solution on Linux.

UPDATE: Obviously, I'm aware of how main() works. Unfortunately, I cannot change the existing application or the way it is invoked (except for CLPs). I can only access via a sandboxed plugin code. My question is whether there is a way to get the command line (rather then the environment variables with -D) that the JVM was invoked with.

like image 638
Uri Avatar asked Jun 29 '09 14:06

Uri


2 Answers

Apart from doing it in main in some way I think the only other option that you have would be to drop to the operating system level and execute some commands to get the arguments.

On linux the cmd line arguments for a running process are stored at /proc/pid/cmdline

So to get them you would have to find the process id. See here:

How can a Java program get its own process ID?

Then using this open /proc/pid/cmdline and parse it. The format of this file and an example in c is here:

http://www.unix.com/unix-advanced-expert-users/86740-retrieving-command-line-arguments-particular-pid.html

It might be best to wrap these two calls in one shell script that you call from java.

Please note that this will be extremely non portable and is a bit hacky. But if needs must...

like image 196
Pablojim Avatar answered Oct 09 '22 14:10

Pablojim


The solution is easy once you realize that Java's main method is just another static method that takes a String array as argument.

Create a new class that stores the CLPs, then calls the old class. Later on, you can access your CLPs using the new class:

import NotToBeChangedMainClass;

public MyMainClass {
  public static final String[] ARGUMENTS;
  public static void main(String ... args) {
    ARGUMENTS = args;
    NotToBeChangedMainClass.main(args);
  }

}

Finally, change whatever external caller (e.g. any Batch files) to use MyMainClass instead of NotToBeChangedMainClass. If you are using runable jars or something similar, this requires changing the appropriate configuration file.

like image 41
nd. Avatar answered Oct 09 '22 13:10

nd.