为什么Java(> = 7版本)不支持没有主方法的程序? [英] Why java (>=7 version) does not support to run program without main method?

查看:77
本文介绍了为什么Java(> = 7版本)不支持没有主方法的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class WithoutMain {   
       static
       {           
            System.out.println("Without main class!!!");
            System.exit(0);            
       }
}

当我试图在高于7的Java版本中运行以上代码时,出现以下错误. 该程序已成功编译,但未找到主类.主类应包含以下方法:public static void main(String [] args).

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).

有人可以指导我为什么在Java7之后Java不支持在没有main的情况下运行程序

can someone please guide me why Java does not support to run program without main after java7

推荐答案

AFAIK,此更改特定于Java7.在Java 8中,您可以执行此操作.您无法在Java 7中执行此操作,因为Java 7在不首先加载失败的类的情况下查找方法.无论如何,它都已在Java 8中进行了更改.

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);
    }
}

打印

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.

这篇关于为什么Java(> = 7版本)不支持没有主方法的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆