How to call JAVA class methods using shell script? [duplicate] - java

This question already has answers here:
Calling Java Methods from Shell Scripts
(4 answers)
Closed 5 years ago.
I have been working on a solution. Need to call a method written in JAVA program using a shell script command. Is there a way to call non main methods.
I'm using a .sh file's to (start & stop) the program. By any way can i write a script to call the non "Main" method.

Only main method can be called from shell script.
Example is:
class Test
{
public static void main(String []arg)
{
String input = arg[0];
if ("start".equals(input))
//call start method
else if ("stop".equals(input))
//call stop method
else
//define default behaviour
}
}
Shell
java -cp /path/class Test start
This will call main method of the Test class and pass start as argument.
And -cp represents path to java class file.
Assumption is that java's path is already set in environment.
EDIT : You can not call non main method directly, instead you can pass argument to main method and based on the input(use if-else) call method to start or stop

If you want to call a method from shell it is definitely an entry point for your application. Simply write a class with main method which calls the desired method, build your jar and execute it as a regular java application.

Given the following MyFirstJavaProgram.java
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
And a correctly installed Java on your computer, you can do the following
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

There are several options:
a simple method would be: you "fix" somehow the methods to invoke. Like: your main class parses a numerical argument, that you then use to "lookup" the method to invoke from within a table for example
you can use reflection to implement a single main() method that reads the names of methods (and even the name of the enclosing class) from the command line, to then execute "by name"
you can avoid reflection, and basically have one main() method per "other method" you want to invoke (of course that means that you end up with plenty of classes - each one having one main() inside
you could look into jython: this tool allows you to run a python interpreter inside a specific JVM instance.
The jython solution might be more work - but in case you are trying to solve a "real world" problem, this should be your first choice.

Related

Why there is no "public static void main" required to start an RFT script?

I was wondering how RFT works even though it doesn't contain any public static void main(String[] args) in the script. The script contains a method public void testMain(Object[] args) which is running the script. Can someone explain how this is happening in RFT even though there is no public static void main?
A Java program has not a fixed entry point. In fact, you can call any method you want, given it is accessible. What method is called is up to the application that is making the call.
What happens is that the java command line tool, as stated in the docs:
The java command starts a Java application. It does this by starting
the Java Runtime Environment (JRE), loading the specified class, and
calling that class's main() method. The method must be declared public
and static, it must not return any value, and it must accept a String
array as a parameter.
This is just the java tool behaviour. Other tools can an do behave differently.
There is no main() method because you don't run the RFT script as a Java application. You actually start some part of RFT which then calls the testMain() method. The RFT part you start contains a main() method. You can compare it with JUnit test cases: you run the JUnit framework and all your annotated test methods are called. In RFT you run the RFT part and your testMain() method gets called.

execute method in cmd without main function

I need to execute a method in .java or .class but this class doesn't have a main function (I can't use main function because it has no return value) I must execute this method in cmd , Is there any way to resolve this problem ?
First of all: Java has methods, not functions.
Up until Java 7, it was possible to run Java without a main method using the static block, but this was removed as of Java 7, because the static block was not supposed to use this way.
If you want to run it: add a main method.
If you want to call Java class from Python and get result from it, then you should use something like JPype or Pyjnius.
See Calling Java from Python

How does the main method work?

I'm the product of some broken teaching and I need some help. I know that there is this thing called the "main method" in Java and I'm sure other programming languages. I know that you need one to make your code run, but how do you use it to make your run? What does it do and what do you need to have it put in it to make your code run?
I know it should look something like this.
But almost nothing more.
static void main(String[] args){
}
Breaking this down, point-by-point, for the general case:
All Java applications begin processing with a main() method;
Each statement in the main executes in order until the end of main is reached -- this is when your program terminates;
What does static mean? static means that you don't have to instantiate a class to call the method;
String[] args is an array of String objects. If you were to run your program on the command line, you could pass in parameters as arguments. These parameters can then be accessed as you would access elements in an array: args[0]...args[n];
public means that the method can be called by any object.
its the entry point for any java program, it does whatever you tell it to do. all you need to do is declare it in one of your source java files and the compiler will find it.
Firstly it should be public static void main(String[] args){...}.
It must be public
Take a look at The main method
The JVM will look for this method signature when it runs you class...
java helloWorld.HelloWorld
It represents the entry point for your application. You should put all the required initialization code here that is required to get your application running.
The following is a simple example (which can be executed with the command from above)
package helloWorld;
public class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Summary
void means the method returns no value. String[] args represents a string of arguments in an Array type that are passed to the program. main is the single point of entry in to most Java programs.
Extended
Glossing over why it should be public static void... (You wouldn't build a door without a doorknob), methods (equivalent of functions (or subs) in other languages) in Java have a return type. It just so happens that the main method in Java has to return void. In C or C++, the main method can return an int and usually this indicates the code status of the finished program. An int value of 0 is the standard for a successful completion.
To get the same effect in Java, we use System.exit(intValue)
String[] args is a string array of arguments, passed to the main function, usually for specific application use. Usually these are used to modify a default behavior or for flags used in short command line executable applications.
main just means to the JVM, start here! Same name in C and C++ (and probably more).
when you execute your class, anything in the main method runs.
You should have a main class and a main method. And if you want to find something in the console, you need have one output command at least in the method, like :
System.out.println("Hello World!");
This makes the code running lively.

"Error: Main method not found in class MyClass, please define the main method as..."

New Java programmers often encounter messages like the following when they attempt to run a Java program. (Different Java tools, IDEs and so on give a variety of diagnostics for this problem.)
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Error: Main method not found in the file, please define the main method as:
public static void main(String[] args)
Error: Main method is not static in class MyClass, please define the main method as:
public static void main(String[] args)
Error: Main method must return a value of type void in class MyClass, please
define the main method as:
public static void main(String[] args)
java.lang.NoSuchMethodError: main
Exception in thread "main"
What does this mean, what can cause it, and what should one do to fix it?
When you use the java command to run a Java application from the command line, e.g.,
java some.AppName arg1 arg2 ...
the command loads the class that you nominated and then looks for the entry point method called main. More specifically, it is looking for a method that is declared as follows:
package some;
public class AppName {
...
public static void main(final String[] args) {
// body of main method follows
...
}
}
The specific requirements for the entry point method are:
The method must be in the nominated class.
The name of the method must be "main" with exactly that capitalization1.
The method must be public.
The method must be static 2.
The method's return type must be void.
The method must have exactly one argument and argument's type must be String[] 3.
(The argument may be declared using varargs syntax; e.g. String... args. See this question for more information. The String[] argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)
If anyone of the above requirements is not satisfied, the java command will fail with some variant of the message:
Error: Main method not found in class MyClass, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Or, if you are running an extremely old version of Java:
java.lang.NoSuchMethodError: main
Exception in thread "main"
If you encounter this error, check that you have a main method and that it satisfies all of the six requirements listed above.
1 - One really obscure variation of this is when one or more of the characters in "main" is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.
2 - Here is an explanation of why the method is required to be static.
3 - String must be the standard java.lang.String class and not to a custom class named String that is hiding the standard class.
The problem is that you do not have a public void main(String[] args) method in the class you attempt to invoke.
It
must be static
must have exactly one String array argument (which may be named anything)
must be spelled m-a-i-n in lowercase.
Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.
Other answers are doing a good job of summarizing the requirements of main. I want to gather references to where those requirements are documented.
The most authoritative source is the VM spec (second edition cited). As main is not a language feature, it is not considered in the Java Language Specification.
2.17.1 Execution - Virtual Machine Start-up
5.2 Virtual Machine Start-up
Another good resource is the documentation for the application launcher itself:
java - the Java application launcher
If you are running the correct class and the main is properly defined, also check if you have a class called String defined in the same package. This definition of String class will be considered and since it doesn't confirm to main(java.lang.String[] args), you will get the same exception.
It's not a compile time error since compiler just assumes you are defining a custom main method.
Suggestion is to never hide library java classes in your package.
The name of the exception suggests that the program tried to call a method that doesn't exist. In this context, it sounds like the program does not have a main method, though it would help if you posted the code that caused the error and the context in which the code was run.
This might have happened if the user tried to run a .class file or a .jar file that has no main method - in Java, the main method is the entry point to begin executing the program.
Normally the compiler is supposed to prevent this from happening so if this does happen, it's usually because the name of the method being called is getting determined ar run-time, rather than compile-time.
To fix this problem, a new programmer must either add the midding method (assuming still that it's main that's missing) or change the method call to the name of a method that does exist.
Read more about the main method here: http://csis.pace.edu/~bergin/KarelJava2ed/ch2/javamain.html
Generally, it means the program you are trying to run does not have a "main" method. If you are going to execute a Java program, the class being executed must have a main method:
For example, in the file Foo.java
public class Foo {
public static void main(final String args[]) {
System.out.println("hello");
}
}
This program should compile and run no problem - if main was called something else, or was not static, it would generate the error you experienced.
Every executable program, regardless of language, needs an entry point, to tell the interpreter, operating system or machine where to start execution. In Java's case, this is the static method main, which is passed the parameter args[] containing the command line arguments. This method is equivalent to int main(int argc, char** argv) in C language.
I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a
java.lang.NoSuchMethodError: No virtual method
If you are using VSCode:
Choose: Clean Workspace
Choose: Restart and delete
Keep coding :-)
For those who encountered this problem in Kotlin Project.
You can try deleting .idea folder and running the project again - for me it solved the issue. (better close IntelliJ first)
Seems like sometimes IntelliJ gets all confused about the main method signature and expecting the java signature instead of the Kotlin one.
Few min back i was facing " main method not defined".Now its resolved.I tried all above thing but nothing was working.There was not compilation error in my java file.
I followed below things
simply did maven update in all dependent project (alt+F5).
Now problem solved.Getting required result.

Who calls the main function in java?

public static void main(String[] args)
{
boolean t=true;
System.out.println("Before return");
if(t) return;
System.out.println("not execute");
}
In the above code when the return is used then it should return to the function which calls the main function. Who exactly calls the main function?
The Java Virtual Machine.
Java classes are executed within a larger context (a particular JVM as others have noted). Below are some possibilities:
you run java -cp {classpath here} com.example.foo.SomeClass to explicitly select a class for the java application launcher to run
you run java -jar somejar.jar (the class in question will be selected in the .jar file's manifest)
you are working within Eclipse and use debug/run to execute a particular class's main() method.
In all cases the main() method is the canonical entry point to executing code given a particular class. From the docs on the java JVM:
DESCRIPTION
The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method. The method declaration must look like the following:
public static void main(String args[])
The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. By default, the first non-option argument is the name of the class to be invoked. A fully-qualified class name should be used. If the -jar option is specified, the first non-option argument is the name of a JAR archive containing class and resource files for the application, with the startup class indicated by the Main-Class manifest header.
The Java runtime searches for the startup class, and other classes used, in three sets of locations: the bootstrap class path, the installed extensions, and the user class path.
Non-option arguments after the class name or JAR file name are passed to the main function.
The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear. The javaw launcher will, however, display a dialog box with error information if a launch fails for some reason.
You state:
In the above code when the return is used then it should return to the function which calls the main function.
There may not be any other Java function (in fact there usually isn't) which calls the main() function. It's the convention for declaring a well-known entry point. If the JVM is launched to run your class's main() method, then when main() returns, the JVM exits, except in a few special cases, e.g. there are other non-daemon threads running or there is a shutdown hook.
Here's a nice example of invoking main() via JNI_CreateJavaVM.
See Running Java programs...
The JVM uses the main() as the starting point for a program just like the int main() in C++.
Agree with above statements as JVM calls the main method because it is the entry point to any class that has to be loaded in order to execute the class.
Jvm starts main thread to call main method.
Java main() method is invoked by : JVM (JAVA VIRTUAL MACHINE)

Categories