我想在执行main()之前打印“Hello”

时间:2013-09-21 14:17:21

标签: java

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

8 个答案:

答案 0 :(得分: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");
  }
}

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

Hello
Main started

此外,您甚至可以通过调用printHello()来简化此操作,即使没有变量初始化,如下所示:

static {
  printHello();
}

答案 1 :(得分:5)

公共类示例{

static {

    System.out.println("Hello first statement executed first ");
}
  public static void main(String[] args) {
    System.out.println("Main started");
  }
}

答案 2 :(得分:4)

使用静态块:

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

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

输出:

hello
after hello

答案 3 :(得分:4)

public class Test {
  static {
    System.out.println("Hello");
  }

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

输出

Hello
Inside Main

答案 4 :(得分:1)

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

答案 5 :(得分:1)

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

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

答案 6 :(得分:1)

(.) :: (->) ((->) b c) ((->) ((->) a b) ((->) a c))
     ~ (b -> c) -> ((a -> b) -> (a -> c))
     ~ (b -> c) -> (a -> b) -> a -> c

静态变量在程序执行开始时初始化。因此,要初始化它,将调用 printit(); 函数,该函数将被执行,并且“您好,它将在MAIN之前被打印” ,最后一个函数将返回值' 0',最后将在该主块之后执行。

最终输出:

thistype ~ f (f b c) (f (f a b) (f a c))

答案 7 :(得分: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");
    }
}

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