2

I have a jar name MyJar.jar which contains MyFinder.class .This class contains a non-static function named as myFind(). I want to call myFind() from a shell script.

I do already know how to call a particular class with a static main() in a jar file using :

java -jar MyJar.jar MyFinder.class

I need some command like above which can call a non static function

Main motive:

I have a script file and only one jar. In the script I want to make function calls based on particular time. I can code this inside inside jar itself. But if the requirement changes later I have to edit the jar. I dont want this to happen and I just want to edit the script file then

sujit
  • 455
  • 6
  • 12
  • 1
    calling a non static function wouldn´t make sense, because they do belong to an instance of a class, which you wont have when you are trying to start a function in a class as a startpoint, – SomeJavaGuy Mar 21 '16 at 08:03
  • 1)is it possible 2)if not possible: should I change the function to static and suppose it is changed can i have two static methods in a class which can be called independently – sujit Mar 21 '16 at 08:08
  • the solution by nfechner is the only reasonable one in my eyes. You might want to check out what the keyword [static](http://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-a-class) does, because it seems like you don´t know. – SomeJavaGuy Mar 21 '16 at 08:10

1 Answers1

1

The only way to do that, is to include a main method in the class, that calls the wanted method:

public static void main(String[] args) {
  MyFinder myFinder = new MyFinder();
  myFinder.myFind();
}

Edit: Actually, it's not the only way, but really the only practical one..

Edit 2: If you have more than one method to call, hand a parameter into the method:

public static void main(String[] args) {
  MyFinder myFinder = new MyFinder();
  if (args.length > 0) {
    switch (args[0]) {
      case "myFind":
        myFinder.myFind();
        break;
      case "methodB":
        myFinder.methodB();
        break;
      default:
        System.err.println("Unkown target");
        break;
    }
  }
}

Call it like this: java -jar MyJar.jar MyFinder.class myFind

nfechner
  • 17,295
  • 7
  • 45
  • 64