How to Call Method in Jar File with Terminal

How to call method in jar file with terminal?

You can not call any method from terminal or cmd of any class.

You can execute class through terminal.

If your jar is executable try: java -jar "Name of your Jar"

Or set the class path of your jar: java -classpath path-to-jar <package>.<classname>

How to call method in jar file with terminal?

You can not call any method from terminal or cmd of any class.

You can execute class through terminal.

If your jar is executable try: java -jar "Name of your Jar"

Or set the class path of your jar: java -classpath path-to-jar <package>.<classname>

Call java class method from jar (not main)

If you are talking about running Java code from the command-line, then no.

You can specify a class name, but not which method to call, that always has to be public static void main(String[] argv).

What you could do is write a helper class (or script like BeanShell) to do that.

java -cp theJar.jar;.  my.helper.WrapperClass theClassToCall theMethodtoCall arg1 arg2

Run class in Jar file

Use java -cp myjar.jar com.mypackage.myClass.

  1. If the class is not in a package then simply java -cp myjar.jar myClass.

  2. If you are not within the directory where myJar.jar is located, then you can do:

    1. On Unix or Linux platforms:

      java -cp /location_of_jar/myjar.jar com.mypackage.myClass

    2. On Windows:

      java -cp c:\location_of_jar\myjar.jar com.mypackage.myClass

Run jar file in command prompt

Try this

java -jar <jar-file-name>.jar

How to run a class from Jar which is not the Main-Class in its Manifest file

You can create your jar without Main-Class in its Manifest file. Then :

java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2 /home/myhome/datasource.properties /home/myhome/input.txt

Calling a static method inside a class in jar file

You could use Jshell:

$ jshell --class-path  ~/.m2/repository/org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar
| Welcome to JShell -- Version 11.0.4
| For an introduction type: /help intro

jshell> org.apache.commons.lang3.StringUtils.join("a", "b", "c")
$1 ==> "abc"

Or create a java class with main compile it and run with java:

Test.java:

class Test {
public static void main(String[] args) {
String result = org.apache.commons.lang3.StringUtils.join("a", "b", "c");
System.out.println(result);
}
}

Compile and run:

$ javac -cp /path/to/jar/commons-lang3-3.9.jar  Test.java
$ java -cp /path/to/jar/commons-lang3-3.9.jar:. Test
abc


Related Topics



Leave a reply



Submit