![](/img/trans.png)
[英]How to access private variable of super class by using lombok SuperBuilder
[英]Access private inner class with Lombok
讓我們用一個靜態內部類來學習下面的類。
@Getter
@Setter
public class Request {
private String contactUrl;
private Resources resources;
@Getter
@Setter
private static class Resources {
private String basketId;
private String customerId;
}
}
我需要像這樣從另一個類訪問basketId
:
Request request = new Request();
request.getResources.setBasketId("5");
這不會編譯,除非我將Resources
類定義為public
。
在保持Resources
私有的同時,還有其他方法可以使用 Lombok 訪問該字段嗎?
您可以使用@Delegate
有效地將私有內部類所具有的每個方法“復制”到外部(並且實現只是在內部調用該方法):
@Delegate private Resources resources;
請注意,在簽名(構造函數、字段、方法等——類型的非代碼方面)中使用一個類型,使得該類型比簽名更不可見,這真的很奇怪:這里你有一個公共方法向不在這個文件中的所有代碼返回一個有效的不可見類型(資源)。 這是一個壞主意; 沒有人可以有用地調用此方法。 要么擺脫 getter 和 setter(例如,改用 Delegate),要么公開 Resources 內部類。
讓我們退后一步:你想要完成什么? 例如,如果您不希望任何人在外部不知情的情況下使用該內部 Resources 類,這很容易做到:只需在 Resources 中創建一個私有構造函數,然后,瞧。 現在除了你的外層沒有人可以制造實例。
為了保持Resources
私有,您可以委托 setter 方法,例如:
@Getter
@Setter
public class Request {
private String contactUrl;
private Resources resources;
@Getter
@Setter
private static class Resources {
private String basketId;
private String customerId;
}
public setBasketId(String id) {
resources.setBasketId(id)
}
}
或者您可以使用反射: Set private field value with reflection
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.