2011-06-05 46 views
1
 
public class Customer { 
    private User user; 
    private String name; 

    public User getUser() { 
     return user; 
    } 

    public void setUser(User user) { 
     this.user = user; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

} 

public class User { 
    private String name; 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

} 


public static void main(String[] args) { 
     try { 
      Customer customer = new Customer(); 

      Object tree = Ognl.parseExpression("user.name"); 

      Ognl.setValue(tree, customer, "hello"); 

     } catch (OgnlException e) { 
      e.printStackTrace(); 
     } 
} 

ognl.OgnlException: target is null for setProperty(null, "name", hello) 

how to let ognl to create user auto. 

回答

0

試試這個

public static void main(String[] args) { 
    try { 
     Customer customer = new Customer(); 
     User user = new User(); 
     customer.setUser(user); 

     Object tree = Ognl.parseExpression("user.name"); 

     Ognl.setValue(tree, customer, "hello"); 

    } catch (OgnlException e) { 
     e.printStackTrace(); 
    } 
} 

與樣品代碼的問題是,你的實例「客戶」有一個空的用戶。所以OGNL本質上是調用customer.getUser()。setName(「hello」),其中「customer.getUser()」返回null。