2

我什至想在 Java 程序中执行"Hello"之前打印。main()有没有办法做到这一点?

4

8 回答 8

9

你需要的是一个static关键字。一种选择是使用静态函数作为静态变量的初始化器。

class Main {
  public static int value = printHello();
  public static int printHello() { 
    System.out.println("Hello"); 
    return 0;
  }
  public static void main(String[] args) {
    System.out.println("Main started");
  }
}

valuemain是一个静态变量,因此在函数执行之前初始化。该程序打印:

Hello
Main started

此外,您甚至可以通过printHello()在没有变量初始化的情况下调用来简化这一点,如下所示:

static {
  printHello();
}
于 2013-09-21T14:20:01.403 回答
5

公共类样本{

static {

    System.out.println("Hello first statement executed first ");
}
  public static void main(String[] args) {
    System.out.println("Main started");
  }
}
于 2014-08-06T11:35:05.900 回答
4

使用静态块:

static {
    System.out.println("hello");
}

public static void main(String[]args) {
    System.out.println("After hello");
}

输出:

hello
after hello
于 2013-09-21T14:20:48.970 回答
4
public class Test {
  static {
    System.out.println("Hello");
  }

  public static void main(String[] args) {
    System.out.println("Inside Main");
  }
}

输出

Hello
Inside Main
于 2013-09-21T14:22:11.697 回答
1

在静态代码块内打印语句。当类被加载到内存中时,甚至在创建对象之前,静态块就会被执行。因此它将在 main() 方法之前执行。并且只会执行一次。

于 2013-09-21T14:24:28.740 回答
1

除了使用静态块,您还可以尝试检测和 premain

http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html

于 2013-09-21T15:37:55.180 回答
1
import java.io.*;


class ABCD {

    public static int k= printit();

    public static  int printit(){

        System.out.println("Hello it will be printed before MAIN");
        return 0;

    }

    public static void main (String[] args) {

        System.out.println("Main method is Executed");

    }
}

静态变量在程序开始执行时被初始化。所以初始化它会调用printit(); 将执行的函数和“Hello it will be print before MAIN”将被打印,并且在最后一个函数中将返回值'0',最后在这个主块之后将被执行。

最终输出:

Hello it willl be printed before MAIN
Main method is Executed
于 2018-08-25T16:44:57.880 回答
0

这是另一种方式:

class One{
    public One() {
        System.out.println("Before main");
    }   
}

class Two extends One{
    public Two() {
        super();
    }
    public static void main(String[] args) {
        Object abj = new Two();
        System.out.println("in the main");
    }
}

在运行配置中,第二类将是主类。

于 2017-01-23T11:43:14.677 回答