I am using a servlet to do a range of things.
If a particular parameter "t" does not exist I want to do certain types of processing, if it does I want to do different things.
I am trying to test the parameter t (which I save as a String called editType), using the following condition:
开发者_如何学GoString editType = request.getParameter("t");
if(!editType.isEmpty()||!(editType==null)){
//processing here
}
How do I do this test properly, because I am getting the problem of a nullpointerexception, because my code always seems to expect a value for "t" I need to be able to create a condition which doesn't expect t (allows it to be null), and do processing in that.
You need to re-order your comparison a bit, in particular to check for null
first:
String editType = request.getParameter("t");
if(editType!=null && !editType.isEmpty()){
//processing here
}
The problem you are having is that Java is trying to call the isEmpty()
method on a null
object, which is why you need to check for null
first.
Java uses Short-circuit evaluation, meaning it will check your conditions from left to right, and as soon as it finds one that would let it decide the result of the entire condition, it will stop evaluating. So if editType
ends up being null, Java will stop evaluating the entire if
statement and won't try to call isEmpty()
(which would result in a NullPointerException
).
Ah, I see you tagged nullpointerexception
so I make a guess. You should test for null first, then emptiness after:
if (editType != null || !editType.isEmpty()) {
//processing here
}
However, this will evaluate to true if editType
is an empty string. To get the correct result, you should use AND (&&) instead of OR (||), like this:
if (editType != null && !editType.isEmpty()){
//processing here
}
You should change this to
String editType = request.getParameter("t");
if(editType != null && !editType.isEmpty()){
//processing here
}
It's useful to have some StringUtil class that offers an ifEmpty() method as this is quite common:
public static final class StringUtil {
private StringUtil() {
}
public static boolean isEmpty(String s) {
return s != null && !s.isEmpty();
}
}
Than change you're code to
String editType = request.getParameter("t");
if(!StringUtil.isEmpty(editType)){
//processing here
}
String editType = request.getParameter("t");
if(!(editType == null || editType.isEmpty())){
//processing here
}
To some people this reads better.
First of all the conditions in your if statement are evaluated from left to right. So the first thing it checks is editType.isEmpty() and if editType is null you will have a null pointer exception. So the first part of your if should be editType != null (preferred to !(editType == null)).
You will have a problem running this code.
It's better this way:
String editType = request.getParameter("t");
if(editType!=null&&!editType.isEmpty()){
//processing here
}
null test has to be in the front to avoid the method invocation on null.
精彩评论