开发者

Setting a primitive without getting a warning in Java

I have a Java method. For the sake of being a public forum, I'm going to say that my method is called foo

Bar foo(Boolean flag)
{
   flag = true;
   return new Bar();
}

I get a warning by setting flag. Unfortunately, I have not found a way to suppress such a warning. Is there a "right" way of doing this? Now I know t开发者_运维技巧here are some who will say to simply not use an out parameter. Trust me when I say that I have a good reason for doing it this way. If there's no way around the warning without doing something crazy, I suppose that's fine. I just don't like checking in code with warnings.


You're getting a warning because your assignment is doing nothing useful. You shouldn't check this code in because it doesn't do what you think it does. For example:

Boolean x = false;
Bar bar = foo(x);
System.out.println(x); // Still false

Your code is setting the value of the flag parameter, which won't change anything about the value which is passed in. Java strictly uses pass-by-value, including when it's passing reference (which it's doing here).

If Boolean were mutable you could write:

// Not actually valid
flag.setValue(true);

and change the contents of the object that x referred to in the first snippet of code - but all the wrapper types in Java are immutable.

Now it's not really clear what your higher level purpose is, but basically it's not going to be accomplished by the code you've given - so heed the warning, and change your approach.


You could take a look at the Java Annotations:

http://download.oracle.com/javase/tutorial/java/javaOO/annotations.html

There is the "SuppressWarning" annotation that could help you.

Anyway, a good program shouldn't contain warnings ;)


Maybe I am mistaken, but isn't there an exterior variable similar name to "flag"? In that case it would make sense to adjust it, and use it as

this.setFlag(true)

or

this.flag = true;

in other details Jon gave good answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜