11

在一次采访中,我问过这个问题:不使用 static 和 main 我们如何在控制台上打印消息?有可能吗?

4

8 回答 8

29

您可以定义一个自定义类加载器来打印您的消息:

public class MyClassLoader extends ClassLoader {
    public MyClassLoader(ClassLoader other) {
         super(other);
         System.out.println("Hi there");
         System.exit(0);
    }
}

然后运行 ​​java 命令:

java -Djava.system.class.loader=MyClassLoader

(不需要添加类作为参数)

于 2013-08-29T08:46:29.867 回答
2
I have asked this question:Without using static and main how could we print
message on console?Is it possible?

Answer is No!

You cannot execute anything unless main() method is called. Prior to Java 7 classes were loaded before main() method was looked up. So you could print your data through static blocks(static block gets executed when classes are loaded) but from java 7 onward even that is not possible. So you always have to execute the main() method first.

Even in frameworks like Spring beans are generally initialized only when it's context is referenced(again main() is required to be executed first).So there is no way you can print something to console without invoking main() method or through static functions/blocks.

于 2013-08-29T08:44:47.317 回答
0

可以使用在 main 方法之前执行的静态块

于 2013-08-29T11:37:05.133 回答
0

答案肯定是否定的。

至少要么你需要一个静态块,要么你需要一个空的 main()。

请参阅以下示例:

1.

public class ABC {
    static{
             System.out.println("hai");
          }
    public static void main(String[] args) {}
}

输出:

2.

public final class ABC {
    static{
             System.out.println("hai");
          }
}

它会在运行时打印“hai”,但之后也会出现一个异常。

输出:

java.lang.NoSuchMethodError:主要

线程“主”中的异常

于 2013-08-29T09:21:22.617 回答
0

Java 是一种 OOP 语言。

如果不创建类并将其添加为静态主函数,则无法创建程序。

然后,您可以调用System.out.println打印一行。

所以,答案是否定的。

于 2013-08-29T08:19:43.363 回答
0

您总是需要syso输入一段代码,也许:

public class example { public void message(){ System.out.println("Hello"); } }

这里的方法不是静态的

于 2013-08-29T08:22:30.240 回答
0
public class Test {
    public static PrintStream ps = System.out.printf("%s", "hello");
}

很奇怪的面试问题。它将打印 hello 并抛出Exception in thread "main" java.lang.NoSuchMethodException.

于 2013-08-29T08:42:01.197 回答
0

@Aniket Thakur 因为我的观点,我无法发表评论。但以下程序会在消息进入主程序之前打印消息。注意:我使用了 Java 7 和 Java 8。两者都工作正常,并且在 main 之前运行静态块。

public class PrintBeforeMain {

    private static int i = m1(); 

    public static int m1(){ 
        System.out.println("m1(): Before main() through static method..."); 
        return 0; 
    }

    static{
        System.out.println("Inside standalone static{} block");
    }

    public static void main(String[] args) {
        System.out.println("Inside main()");
    }
}
于 2015-06-19T13:30:24.523 回答