为什么 Java 只允许 String[] args 作为 Main 方法参数?
Why Java Only Allows String[] args as Main method Argument?
为什么Java只允许main方法采用String[] args
形式的参数?即字符串数组
public static void main(String[] args)
为什么 Java 不允许像
这样的 int 或 double 数组
public static void main(int[] args)
或
public static void main(double[] args
为什么它不允许单个字符串或 int 或 float 而不是字符串数组?类似于:
public static void main(String args)
或
public static void main(int i)
这就是您在命令行中 运行 java 程序的方式:
java YourMainClass
命令行参数在后面:
java YourMainClass arg1 arg2 arg3
这将使 args
字符串数组包含 "arg1"
、"arg2"
和 "arg3"
。如果将 args
数组设为 int[]
,arg1
将如何放入 int
?
从 JVM 的角度来看,将命令行参数放在 String
s 中是最安全的选择。用户输入的任何内容,都必须是一堆 char
s.
根据 JLS,
第 12.1.4 节:
Finally, after completion of the initialization for class Test (during
which other consequential loading, linking, and initializing may have
occurred), the method main of Test is invoked.
The method main must be declared public, static, and void. It must
specify a formal parameter (§8.4.1) whose declared type is array of
String.
为什么Java只允许main方法采用String[] args
形式的参数?即字符串数组
public static void main(String[] args)
为什么 Java 不允许像
这样的 int 或 double 数组public static void main(int[] args)
或
public static void main(double[] args
为什么它不允许单个字符串或 int 或 float 而不是字符串数组?类似于:
public static void main(String args)
或
public static void main(int i)
这就是您在命令行中 运行 java 程序的方式:
java YourMainClass
命令行参数在后面:
java YourMainClass arg1 arg2 arg3
这将使 args
字符串数组包含 "arg1"
、"arg2"
和 "arg3"
。如果将 args
数组设为 int[]
,arg1
将如何放入 int
?
从 JVM 的角度来看,将命令行参数放在 String
s 中是最安全的选择。用户输入的任何内容,都必须是一堆 char
s.
根据 JLS,
第 12.1.4 节:
Finally, after completion of the initialization for class Test (during which other consequential loading, linking, and initializing may have occurred), the method main of Test is invoked.
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.