[英]No Constructor Found Java + Lombok
主要的
public static List<Viking> uploadVikings(){
List<Viking> vikings = new ArrayList<Viking>();
vikings.add(new Viking("Lean",23,100, new DrinkVikingImp(), new PeeVikingImp(),10));
vikings.add(new Viking("Thor",24,99, new DrinkVikingImp(), new PeeVikingImp(),9));
vikings.add(new Viking("Thanos",25,98, new DrinkVikingImp(), new PeeVikingImp(),9));
vikings.add(new Viking("Hulk",26,97, new DrinkVikingImp(), new PeeVikingImp(),5));
vikings.add(new Viking("Thrall",27,96, new DrinkVikingImp(), new PeeVikingImp(),3));
return vikings;
}
維京 Class
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Viking extends Human{
public Integer proDrinker;
public Pee pee;
public Drink drink;
public void pee() {pee.pee();}
public void drink() {drink.drink();}
}
人類 Class
@Data
@AllArgsConstructor
@NoArgsConstructor
public abstract class Human {
public String Name;
public Integer Age;
public Integer Weight;
}
喝水和尿尿的界面是一樣的
public class DrinkVikingImp implements Drink {
@Override
public void drink() {
System.out.println("Viking is Drinking");
}
}
Error: Error:(21, 21) java: no suitable constructor found for Viking(java.lang.String,int,int,com.company.models.DrinkVikingImp,com.company.models.PeeVikingImp,int)
constructor com.company.models.Viking.Viking() is not applicable
(actual and formal argument lists differ in length)
constructor com.company.models.Viking.Viking(java.lang.Integer,com.company.interfaces.Pee,com.company.interfaces.Drink) is not applicable
(actual and formal argument lists differ in length)
你可以使用 Lombok 的 builder 生成器(@SuperBuilder 注解)來解決這個問題,它是在 1.18 版本中引入的
@Data
@SuperBuilder
public abstract class Human {
...
}
@Data
@SuperBuilder
public class Viking extends Human {
...
}
然后你就可以構建你的 Viking 對象,如下所示:
vikings.add(Viking.builder()
.name("Lean")
.age(23)
.weight(100)
.drink(new DrinkVikingImp())
.pee(new PeeVikingImp())
.proDrinker(10)
.build());
還要檢查您的 Human class 字段名稱,它們不應以大寫字母開頭。
從龍目島:
@AllArgsConstructor 為 class 中的每個字段生成一個帶有 1 個參數的構造函數。
根據錯誤信息
com.company.models.Viking.Viking(java.lang.Integer,com.company.interfaces.Pee,com.company.interfaces.Drink) is not applicable
你可能需要這個
vikings.add(10, new Viking(new DrinkVikingImp(), new PeeVikingImp()));
vikings.add(9, new Viking(new DrinkVikingImp(), new PeeVikingImp()));
vikings.add(9, new Viking(new DrinkVikingImp(), new PeeVikingImp()));
vikings.add(5, new Viking(new DrinkVikingImp(), new PeeVikingImp()));
vikings.add(3, new Viking(new DrinkVikingImp(), new PeeVikingImp()));
然后你必須自己設置人類屬性
這在龍目島是不可能的。 雖然這將是一個非常好的功能,但它需要解決才能找到超級 class 的構造函數。 超級 class 只有在 Lombok 被調用時才知道名稱。 使用導入語句和類路徑來查找實際的 class 並非易事。 在編譯期間,您不能只使用反射來獲取構造函數列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.