了解下Java中main方法参数args

Olinda ·
更新时间:2024-09-20
· 894 次阅读

以下用spring boot项目做一个示例:

这是spring boot的启动类

public class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); } }

可以看到它的main方法上有参数args。

这时如果我们想在项目启动时传入参数到这个main方法,然后根据参数的不同来做相应的逻辑,以下做个传参的示例:

public class SpringbootApplication { public static void main(String[] args) { //打印出参数 for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } SpringApplication.run(SpringbootApplication.class, args); } }

我用的开发工具是idea,接下来做个启动时参数设置:

点击进去修改配置

在这里插入图片描述

设置参数为hello world
在这里插入图片描述
启动项目,看下效果:
在这里插入图片描述
可以看到参数hello world被打印了出来,也就是说参数成功的进入了这个启动类的main方法中,之后就可以根据业务需要来设置参数了

总结

要知道,main方法是给虚拟机识别并调用的,开发不能手动调用main方法,所以如果真的需要在main方法中传参数,通过以上方法也是能够做到的,当然通过 java xxx hello world 这样的命令行效果也是一样的,用这种方法做骚操作的话,还可以对启动加密,比如这样玩:

public class SpringbootApplication { public static void main(String[] args) throws Exception { for (int i = 0; i < args.length; i++) { System.out.println(args[i]); } //校验是不是admin的用户 if (!"admin".equals(args)) { throw new Exception(); } SpringApplication.run(SpringbootApplication.class, args); } }

启动就会报错:
在这里插入图片描述
综上,反正存在即合理,了解一下没问题。


作者:绅士jiejie



main JAVA

需要 登录 后方可回复, 如果你还没有账号请 注册新账号