views:

125

answers:

3

Hi all,

I try to run a jar using reflection with the the getMethod and invoke method but ran in trouble with the arguments passed to the invoke method:

String mainClass = myprog.Run;
String[] args = new String[2];
args[0] = "-a";
args[1] = "-c ./config/param.xml"

ClassLoader classLoader = createClassLoader(getClassPath());

// Invoke the method
setContextClassLoader(classLoader);
Class<?> theClass = classLoader.loadClass(mainClass);

theClass.getMethod("main", String[].class).invoke(null, (Object) args);

and I get this error:

 [java] java.lang.reflect.InvocationTargetException
 [java]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 [java]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 [java]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 [java]     at java.lang.reflect.Method.invoke(Method.java:597)
 [java]     at eu.keep.util.JarRunner.run(Unknown Source)
 [java] Caused by: java.lang.RuntimeException: config file 'param.xml' does not exist in folder '/home/user/ ./config'
 [java]     at dioscuri.DioscuriFrame.<init>(Unknown Source)
 [java]     at dioscuri.DioscuriFrame.main(Unknown Source)
 [java]     ... 5 more

As you can see from the stacktrace, it is trying to access the file 'param.xml' from the folder '/home/user/ ./config'.

Obviously, if the space between '/home/user/' and './config' was not there, it would all be fine.

I am confused with the fact that I have hardcoded the arguments into String[] args and the second one is "-c ./config/param.xml" and it looks like the dir from which the app is running, i.e. /home/user/, gets concatenated with ./config/ but with a space in between ??

Any idea what is happening ?

David

+1  A: 
String[] args = new String[3];
args[0] = "-a";
args[1] = "-c";
args[2] = "./config/param.xml"

But please provide the code which causes the exception.

Bozho
+1  A: 

Maybe if we have a look at your main method, and in particular the way the arguments are managed, we could help you in a better way...

Note that when you run your main class with the command java ... -a -c ./config/param.xml, then you have 3 arguments in your main(String[] args) method:

public static void main(String[] args) {
    for (String s : args) {
        System.out.println("-> '" + s + "'");
    }
    ...

will display:

-> '-a'
-> '-c'
-> './config/param.xml'
romaintaz
indeed, like other answers suggest it ! stupid me. thanks guys
DavidM
+1  A: 

The -c and ./config/param.xml need to be in separate array elements.

Jim Garrison