我有三个模型类MyApp,Product和ProductDetails。我正在尝试在ProductDetails中设置值,但出现了空指针异常。有人可以帮我在这里做错什么吗
MyApp.java
public class MyApp {
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
Product.java
public class Product {
private ProductDetails details;
public ProductDetails getDetails() {
return details;
}
public void setDetails(ProductDetails details) {
this.details = details;
}
}
ProductDetails.java
public class ProductDetails {
private String productName;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
Test.java
public class Test {
public static void main(String[] args) {
MyApp m = new MyApp();
m.getProduct().getDetails().setProductName("testProduct");
System.out.println("Name : " + m.getProduct().getDetails().getProductName());
}
}
我遇到以下异常: Test.main(Test.java:7)上的线程“ main” java.lang.NullPointerExceptio中的异常
答案 0 :(得分:2)
使用前必须先初始化product.details和details.productName。例如:
m.getProduct().setDetails(new ProductDetails());
m.getProduct().getDetails().setProductName(...);
变量m中的产品如何?