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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With