-2

I get NullPointerException when validating object. I send to controller dto, and when validating it. I cant understan where is the problem because product that goes into validate method is not null, Validator code :

@Override
public void validate(Object o, Errors errors) {

    Product product = (Product) o;

    if (product.getTitle().isEmpty() || product.getTitle() == null) {
        errors.rejectValue("title", "product.title", "Product title cant be empty");
    }
    if (product.getDescription().isEmpty() || product.getDescription() == null) {
        errors.rejectValue("description", "product.description", "Product description cant be empty");
    }
    if (product.getPrice().isNaN() || product.getPrice()<=0 || product.getPrice() == null) {
        errors.rejectValue("price", "product.price", "Product price is not valid");
    }
    if (product.getCategory()==null) {
        errors.rejectValue("category", "product.category", "Product category is not valid");
    }

}

and i get this

java.lang.NullPointerException com.shop.validator.ProductValidator.validate(ProductValidator.java:27) com.shop.controller.ProductController.createProduct(ProductController.java:82) com.shop.controller.ProductController$$FastClassBySpringCGLIB$$c0d382c4.invoke() org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
qwd412
  • 17
  • 1
  • 4
  • Since the Java code you've posted is obviously not complete source files, could you let us know where line 27 of `ProductValidator` and line 82 of `ProductController` are? – ajb Dec 31 '16 at 21:20
  • if (product.getPrice().isNaN() || product.getPrice()<=0 || product.getPrice() == null) { errors.rejectValue("price", "product.price", "Product price is not valid"); } it is 27th and 82th is productValidator.validate(product,bindingResult); – qwd412 Dec 31 '16 at 21:24
  • Reopened because I don't believe this is a duplicate of "What is a NullPointerException", which is too generic. This question has to do with how short-circuit operators work, and the proposed duplicate doesn't address that. – ajb Dec 31 '16 at 22:59

1 Answers1

2

|| evaluates from left to right. So if you say

x == null || x.somethingSomething()

and if x is null, the first condition will catch the case, and it will prevent the method call on a null reference from happening. But if you say

x.somethingSomething() || x == null

and if x is null, it tries to evaluate the method call first, and throws an exception before it gets to the null check. Java (or any other computer language I'm aware of) isn't smart enough to "figure out" to do the null check first. It trusts the order you give it.

Similarly with &&:

if (x != null && x.something())

will do the null check at the right time, but

if (x.something() && x != null)

won't.

ajb
  • 31,309
  • 3
  • 58
  • 84