Home > Software design >  How to execute a specific method from my java program on cmd?
How to execute a specific method from my java program on cmd?

Time:05-21

I have a java program define like this :

public class MyClass{    
   public String getPathBetween(String path,String folderName,String extension){..}
   public static void main(String[] args) throws Exception{...}
}

After compiling the program using following command :

$ javac MyClass.java

I can run the main method like this :

$ java MyClass

But how can I run the method getPathBetween ?

I tried this , but with no avail :

$ java MyClass.getPathBetween("some text", "some","text")

CodePudding user response:

You need to call the method from main. The entry point of a program is always main.

CodePudding user response:

//You can create an instance of MyClass in your main() method
// and then call getPathBetween():
public class MyClass{    
   public String getPathBetween(String path, String folderName, String extension){..}
   public static void main(String[] args) throws Exception{
      MyClass myClassInstance = new MyClass();
      String path = "/some/path/value";
      String folder = "my-test-folder";
      String extension = "xyz";
      String pathBetween = myClassInstance.getPathBetween(path, folder, extension);
      System.out.println("pathBetween="   pathBetween);
   }
}

Or if you want to be able to pass values into getPathBetween() from the command line, you could change the code to:

public class MyClass{    
   public String getPathBetween(String path, String folderName, String extension){..}
  public static void main(String[] args) throws Exception{
     MyClass myClassInstance = new MyClass();
     String path = args[0];
     String folder = args[1];
     String extension = args[2];
     String pathBetween = myClassInstance.getPathBetween(path, folder, extension);
     System.out.println("pathBetween="   pathBetween);
  }
}

And then run it like so:

java MyClass "some text" "some" "text"
  • Related