4

在java,commons beanutils中,尝试将属性'address'和'creditCardList'设置为对象,但它给了我错误:

java.lang.NoSuchMethodException: Property 'address' has no setter method in class 'class com.dao.Student'

但我有这个方法。代码在这里:

public class Main { 
    public static void main(String[] args) {
        Object student = new Student("John");       
        Object address = new Address("NJ");

        try {
            PropertyUtils.setProperty(student, "address", address);         
            //---------- 
            List list = new ArrayList();
            Object creditCard = new CreditCard();
            list.add(creditCard);

            PropertyUtils.setProperty(student, "creditCardList", list);         

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

class Student {
    private String name;        
    private Address address;    
    private List<CreditCard> creditCardList;    
    public Student(String name) {
        super();
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public List<CreditCard> getCreditCardList() {
        return creditCardList;
    }
    public void setCreditCardList(List<CreditCard> creditCardList) {
        this.creditCardList = creditCardList;
    }   
}

class Address {
    private String name;
    public Address(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

class CreditCard{
    private String cardName;

    public String getCardName() {
        return cardName;
    }

    public void setCardName(String cardName) {
        this.cardName = cardName;
    }   
}
4

2 回答 2

6

您的班级 Student 应该是 public class ,尝试将其公开并重新运行您的代码。

于 2011-12-01T19:38:20.597 回答
4

我将学生移动到自己的文件并将其公开,效果很好:)

于 2011-12-01T19:28:27.393 回答