开发者

Removing compiler's warning from a method call, advise needed

As part of my Utils class, i have both

public static boolean isStringEmptyOrNull(String... s) {

When testing for a null condition

assertTrue(Utils.isStringEmptyOrNull(null));

I get "The argument of type null should explicitly be cast to String[] for the invocation of the varargs method isStringEmptyOrNull(String...) from type Utils. It could alternatively be cast to开发者_运维技巧 String for a varargs invocation" warning.

I'd rather not case anything though. This test is designed to simulate a condition where argument passed to the method is a null.

Is there a way to remove this warning without changing the signature of the method?


You should probably test both of these cases:

assertTrue(Utils.isStringEmptyOrNull(new String[] { null }));
assertTrue(Utils.isStringEmptyOrNull((String[]) null));

... although it's not clear to me why a method which sounds like it should only take a single string is taking an array of strings in the first place, to be honest.

(Is it obvious to you which of those invocations you meant without the cast? It isn't obvious to me... I'd have to look it up to check.)


If you are trying to mimic the way a client of your library function would call your code, you should take advantage of the fact that they will not call this particular method with the literal "null" (what would be the point?)

Instead, they would pass in some variable or expression. Since that's the case, you can do something like this and avoid casting:

String nullString = null;
assertTrue(Utils.isStringEmptyOrNull(nullString));


You could specifically tell the compiler to ignore the warning using @SuppressWarnings("all").


Well that warning's there for a reason: when you call your method with null argument, since null is all and any type in Java (including Array), the compiler effectively will not know if you're calling the var-args method with an array or a non-array object (each of which is treated differentlly when var-args arguments are used). What you can do is annotate the method with SuppressWarnings("All") and then test for null before doing anything with the argument(s)


Change your test like so:

String nullString = null;
assertTrue(Utils.isStringEmptyOrNull(nullString));

Rather curious why you use a vararg method for this in the first place though...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜