Java – should the main method copy input parameters?

One can imagine this Code:

public static void main(final String[] args) {
   // do something
}

It should be

public static void main(final String[] args) {
   String[] argsCopy = doCopy(args);
   // do something
}

(in our company, we have a sonar rule that enforces all methods of response or debate.) I can imagine why it might be important for standard methods, but I couldn't find any benefit when I started the tool's main methods Did I miss anything?

Solution

The reason for copying array parameters is to avoid the possibility of someone modifying the array after verifying its elements This is a very good defense technology to protect you from malicious calls from callers

In this case, however, the caller is the JVM itself If you don't trust the JVM to avoid malicious code, it's a much bigger problem than copying an array can solve

The only exception is when you pass parameters to some of your functions In this case, it is a good idea to make a copy in case some method decides to change the contents of args This is the only case I suggest copying If main is the only place where args is used, no replica is required

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>