开发小额记账APP时遇PrimaryTransaction无合适构造器报错问题
问题原因
你定义的PrimaryTransaction类仅提供了两种构造器:
- 无参构造器:无入参
- 全参构造器:共7个入参,最后一个参数为
PrimaryAccount primaryAccount
你触发报错的代码调用构造器时仅传入了6个参数,缺少了最后一个PrimaryAccount类型的入参,因此JVM找不到匹配参数个数的构造器,抛出参数长度不匹配错误。
解决方案
方案1:调用时补全参数(推荐)
直接将当前上下文中的primaryAccount对象作为第7个参数传入构造器即可,修改报错行代码为:
PrimaryTransaction primaryTransaction = new PrimaryTransaction(date, "Deposit to Primary Account", "Account", "Finished", amount, primaryAccount.getAccountBalance(), primaryAccount);
方案2:新增适配的6参数构造器
如果你的业务场景下创建PrimaryTransaction时不需要立即绑定PrimaryAccount,可以在PrimaryTransaction类中新增一个仅接收6个参数的构造器:
public PrimaryTransaction(Date date, String description, String type, String status, double amount, BigDecimal availableBalance) { this.date = date; this.description = description; this.type = type; this.status = status; this.amount = amount; this.availableBalance = availableBalance; }
注意:如果使用该方案,后续要把该交易记录存入数据库前,需要手动调用setPrimaryAccount()方法绑定关联的账户,否则外键字段为空会导致持久化失败。
内容的提问来源于stack exchange,提问作者Seeschon
相关产品推荐
相关产品推荐

