without main class in java throws error while running [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Printing message on Console without using main() method
Can someone suggest how can a JAVA program run without writing a main method..
For eg:
System.out.println("Main not required to print this");
How can the above line be printed on console without using the public static void main(String arg[]) in the class.

Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:
public class Foo {
static {
System.out.println("Message");
System.exit(0);
}
}
The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:
Exception in thread "main" java.lang.NoSuchMethodError: main
In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:
The program compiled successfully, but main class was not found.
Main class should contain method: public static void main (String[] args).
Here an alternative is to write your own launcher, this way you can define entry points as you want.
In the article JVM Launcher you will find the necessary information to get started:
This article explains how can we create a Java Virtual Machine
Launcher (like java.exe or javaw.exe). It explores how the Java
Virtual Machine launches a Java application. It gives you more ideas
on the JDK or JRE you are using. This launcher is very useful in
Cygwin (Linux emulator) with Java Native Interface. This article
assumes a basic understanding of JNI.

Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0) immediately after printing the message.
As of JDK6 onward, you no longer see the message from the static initializer block; details here.

public class X { static {
System.out.println("Main not required to print this");
System.exit(0);
}}
Run from the cmdline with java X.

Applets from what I remember do not need a main method, though I am not sure they are technically a program.

Related

From shell, is there a Java tool to check which compiled .class file(s) have a main method?

I'm putting together some (Python) scripts to help me automate some of my grading of hundreds of simple student Java repos. Not all of them have the same directory structure or naming of files. I've traversed them all and compiled them and if I make assumptions I can run them and test them, etc. But I'd like to know if there's a way I could find the "main" .class that has the main() method in it, so that I don't have to make assumptions about their file naming (which wouldn't work all the time anyway).
I'm aware of reflection, so yes, I know I could write another simple helper Java program to assist me in identifying it myself. But I was wondering if anything already exists (java command line option, tool from the jdk, etc.) to test a .class file to see if it is has the main() method in it.
I was wondering if anything already exists (java command line option, tool from the JDK, etc.) to test a .class file to see if it is has the main() method in it.
There is no tool or option in Java SE that does that directly.
I know I could write another simple helper Java program to assist me ...
It would be simpler to write a shell script that iterates a file tree, finds .class files, calls javap on them, and greps for a method with the appropriate main method signature.
Or you could do something similar on the source code tree.
(In retrospect, you should have set the assignment requirements so that the students had to use a specified class and package name for the class containing their main method. But it is too late for that now ...)
In the C++ days, distributing the headers files to use a shared object file was a big deal. People would get one or the other without both, and there was always the chance you'd get mis-matched versions.
Java fixed that with javap which prints the methods (and other major interfaces) of a compiled .class file.
To test if a class file has a main, run
javap SomeFile.class
which will list all public interfaces. Within that list, see if it has the "main entry point"
public static void main(java.lang.String[])
Now to handle this in mass, simply create a Python script that:
Locates all the relevant classes.
Runs javap on the class.
Reads the output for a method that matches (at the beginning, as there can be a variable number of Exceptions at the end "public static void main(java.lang.String[])
And you'll find all entry points.
Keep in mind that sometimes a single library or JAR file has many entry points, some of which are not intended as the primary entry point.
Well simply calling java -cp . <file> will either completely blow out if the class doesn't have a main method or will run the relevant code. Now, if the code fails to run right and errors out you may see it as the same effect as not having a main method.
public class HasMain {
public static void main(String[] args) {
System.out.println("Hit main");
}
}
public class HasDoIt {
public static void doIt(String[] args) {
System.out.println("Hit doIt");
}
}
public class WillBlowUp {
public static void main(String[] args) {
System.out.println("Hit blowUp");
throw new IllegalStateException("oops");
}
}
Using PowerShell:
PS D:\Development\sandbox> javac HasMain.java
PS D:\Development\sandbox> javac HasDoIt.java
PS D:\Development\sandbox> javac WillBlowUp.java
PS D:\Development\sandbox> java -cp . HasMain
Hit main
PS D:\Development\sandbox> $?
True
PS D:\Development\sandbox> java -cp . HasDoIt
Error: Main method not found in class HasDoIt, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
PS D:\Development\sandbox> $?
False
PS D:\Development\sandbox> java -cp . WillBlowUp
Hit blowUp
Exception in thread "main" java.lang.IllegalStateException: oops
at WillBlowUp.main(WillBlowUp.java:4)
PS D:\Development\sandbox> $?
False
So simply checking return values could be a quick way to test if the class has what you want, albeit any exit(1) type return will throw a false-false

Why java (>=7 version) does not support to run program without main method? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
class WithoutMain {
static
{
System.out.println("Without main class!!!");
System.exit(0);
}
}
when I am trying to to run above code in java version greater than 7 i am getting below error.
The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).
can someone please guide me why Java does not support to run program without main after java7
AFAIK this change was specific to Java 7. In Java 8 you can do this. You can't do this in Java 7 as it looks for the method without loading the class first which fails. In any case, it has been changed back in Java 8.
public class Main {
static {
System.out.println("Without main class!!! with " + System.getProperty("java.version"));
System.exit(0);
}
}
prints
Without main class!!! with 1.8.0_66
Note: this will kill the whole program. If you want the program to keep running without a main you can do this
public class Main {
static {
// do something which starts threads
System.out.println("Without main class!!! with " + System.getProperty("java.version"));
if (true)
throw new ThreadDeath();
}
}
This will prevent the error message, but leave background threads running provided there is a non-daemon thread.
the static section
static
{
System.out.println("Without main class!!!");
System.exit(0);
}
will be executed every time the JVM load the class in memory, but if you want to start a java application, you will need a main method, because that it the start point of every java application, if you dont define it, then the JVM will have no idea where to start.
you can expand your code and do something like:
class WithoutMain {
static
{
System.out.println("Static section!!");
}
public static void main(String[] args){
System.out.println("Main class!!!");
}
}
and the output will be the static section first and then the code you define in the main method.
Static method is loaded with the class each time the JVM is started and the class is loaded into it, but there is nothing that calls it or outputs its contents inside of the JVM. As every language (that I know), you need a handler for your arguments and in case of Java, it is the main() method.

Java program without main method above JDK 1.6 [duplicate]

This question already has answers here:
How can you run a Java program without main method? [duplicate]
(4 answers)
Closed 8 years ago.
Is it possible to run a java program without main method ?
How can I execute this Java program in eclipse?
public class A {
static {
System.out.println("hello");
System.exit(0);
}
}
There are some ways to "run a Java program" without main method.
For example:
you could create a jUnit test. In that case Eclipse will offer you the option "Run as jUnit Test".
you can create a class which extends JApplet. In that case Eclipse will offer the option "Run as Java Applet".
Your question is copied from here, but the answer is :
Use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
or
public class X { static {
System.out.println("Main not required to print this");
System.exit(0);
}}
Run from the cmdline with java X.

ArrayIndexOutOfBoundsException on every main() function I create

This problem only started recently, but all my main functions on various programs don't work (they have worked in the past).
They now all return:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at com.avaje.ebeaninternal.server.lib.sql.Prefix.main(Prefix.java:40)
Here is an example of a class that gives this error:
package PACKAGE_NAME_HERE;
public class SomeClass {
public static void main(String[] args) {
System.out.println("Test");
}
}
You're calling method main in com.avaje.ebeaninternal.server.lib.sql.Prefix (which is part of Maven, source can be found here) from somewhere.
Line 40: String m = e(args[0]);
And if you don't pass any command-line arguments, you don't have args[0], and you got ArrayIndexOutOfBoundsException.
That's all I can tell from your question(can't use comments yet, but more clarification/what did you change recently(anything about Maven?) would be nice).
Deleting the project and making a new one fixed this error. Not sure why, maybe I accidentally messed up the setup or something.

How can you run a Java program without main method? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Printing message on Console without using main() method
Can someone suggest how can a JAVA program run without writing a main method..
For eg:
System.out.println("Main not required to print this");
How can the above line be printed on console without using the public static void main(String arg[]) in the class.
Up to and including Java 6 it was possible to do this using the Static Initialization Block as was pointed out in the question Printing message on Console without using main() method. For instance using the following code:
public class Foo {
static {
System.out.println("Message");
System.exit(0);
}
}
The System.exit(0) lets the program exit before the JVM is looking for the main method, otherwise the following error will be thrown:
Exception in thread "main" java.lang.NoSuchMethodError: main
In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:
The program compiled successfully, but main class was not found.
Main class should contain method: public static void main (String[] args).
Here an alternative is to write your own launcher, this way you can define entry points as you want.
In the article JVM Launcher you will find the necessary information to get started:
This article explains how can we create a Java Virtual Machine
Launcher (like java.exe or javaw.exe). It explores how the Java
Virtual Machine launches a Java application. It gives you more ideas
on the JDK or JRE you are using. This launcher is very useful in
Cygwin (Linux emulator) with Java Native Interface. This article
assumes a basic understanding of JNI.
Up until JDK6, you could use a static initializer block to print the message. This way, as soon as your class is loaded the message will be printed. The trick then becomes using another program to load your class.
public class Hello {
static {
System.out.println("Hello, World!");
}
}
Of course, you can run the program as java Hello and you will see the message; however, the command will also fail with a message stating:
Exception in thread "main" java.lang.NoSuchMethodError: main
[Edit] as noted by others, you can avoid the NoSuchmethodError by simply calling System.exit(0) immediately after printing the message.
As of JDK6 onward, you no longer see the message from the static initializer block; details here.
public class X { static {
System.out.println("Main not required to print this");
System.exit(0);
}}
Run from the cmdline with java X.
Applets from what I remember do not need a main method, though I am not sure they are technically a program.

Categories

Resources