Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute jar without a main?

Can I execute a jar file without having a main class, in this way:

java -jar my_jar.jar -getX arg1 arg2 ...

Knowing that I have a method called getX with takes arg1 arg2 ... as arguments. Any idea?

like image 889
TheForbidden Avatar asked Mar 27 '13 11:03

TheForbidden


People also ask

How do I run a JAR file without main class?

We can run it with any number of arguments. So, when invoking an executable JAR, we don't need to specify the main class name on the command line. We simply add our arguments after the JAR file name.

Does a jar need a main method?

If you're going to execute a jar using " java -jar ", you're going to need to define a main class. You'll need a main class that defines a main method for the jar to be executable this way.

Can JAR file run without JVM?

3 Answers. Show activity on this post. Other than 1) asking them to install Java, or 2) writing your own JVM, the answer is generally no. You have to have a JVM/JRE for your jar file, unless you have a development environment that can create a native executable from your code.


2 Answers

You must have a main method.

The signature for main needs to be:

public static void main(String[] args){
    // Insert code here
}

Therefore, you can call your method getX inside the main method.

like image 93
TheEwook Avatar answered Oct 23 '22 09:10

TheEwook


The short answer is no...but...

Here is a technique you can use to pass a method name and parameters on the command line when invoking the jar. This instructional example will take a method name as the 1st parameter. Tweak as necessary and add error checking/handling as needed.

package com.charles.example;
import java.lang.reflect.Method;

public class MethodRouter {

public void myMethod(final String[] args) {
    System.out.println("Amazing!! " + args[1]);
}

public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        args = new String[2];
        args[0] = "myMethod";
        args[1] = "yoyo-yada-bla";
    }
    final MethodRouter methodRouter = new MethodRouter();
    final Class<?>[] types = { String[].class };
    final Class<?> _class = methodRouter.getClass();
    final String methodName = args[0];
    final Method _method = _class.getDeclaredMethod(methodName, types);
    if (_method != null) {
        _method.invoke(methodRouter, new Object[] { args });
    }
}

}

Output:

Amazing!! yoyo-yada-bla
like image 39
Java42 Avatar answered Oct 23 '22 10:10

Java42