Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a static method inside a class in jar file [duplicate]

Tags:

java

I want to execute specific method inside class in jar file which is don't have main method, with java command I tried java -cp classes.jar com.example.test.Application but I get this error Error: Could not find or load main class After decompile jar file I have found Application class inside it is there any way to call a static function inside Application class in a jar file?

like image 585
Daniel.V Avatar asked Sep 30 '19 13:09

Daniel.V


People also ask

Can a class have 2 static methods in Java?

The answer is 'Yes'. We can have two or more static methods with the same name, but differences in input parameters. For example, consider the following Java program.

Is static method called only once?

Static method does not mean it runs only once. static means it can be access outside method without instantiating an instance of the class.

Can we call static method multiple times?

@SangitGurung it's not. The methods are executed in separate activation frames.

How do you call a non static method into another non static method without an object?

But when we try to call Non static function i.e, TestMethod() inside static function it gives an error - “An object refernce is required for non-static field, member or Property 'Program. TestMethod()”. So we need to create an instance of the class to call the non-static method.


1 Answers

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
like image 152
i.bondarenko Avatar answered Oct 12 '22 23:10

i.bondarenko