简体   繁体   English

使用 Lombok 访问私有内部类

[英]Access private inner class with Lombok

Let's take the following class with a static inner class.让我们用一个静态内部类来学习下面的类。

@Getter
@Setter
public class Request {
    private String contactUrl;
    private Resources resources;

    @Getter
    @Setter
    private static class Resources {
        private String basketId;
        private String customerId;
    }
}

I need to access the basketId from another class like this:我需要像这样从另一个类访问basketId

Request request = new Request();
request.getResources.setBasketId("5");

This won't compile unless I define the Resources class as public .这不会编译,除非我将Resources类定义为public

Is there any other way using Lombok accessing this field while keeping Resources private?在保持Resources私有的同时,还有其他方法可以使用 Lombok 访问该字段吗?

You can use @Delegate to effectively 'copy' every method that your private inner class has to the outer (and the implementation just calls that method on the inner):您可以使用@Delegate有效地将私有内部类所具有的每个方法“复制”到外部(并且实现只是在内部调用该方法):

@Delegate private Resources resources;

Note that having a type used in a signature (the constructors, fields, methods, etc – the non-code aspects of a type) such that the type is less visible than the signature, is really weird : Here you have a public method that returns an effectively invisible type (Resources) to all code that isn't in this very file.请注意,在签名(构造函数、字段、方法等——类型的非代码方面)中使用一个类型,使得该类型比签名更不可见,这真的很奇怪:这里你有一个公共方法向不在这个文件中的所有代码返回一个有效的不可见类型(资源)。 This is a bad idea;这是一个坏主意; nobody can usefull call this method.没有人可以有用地调用此方法。 Either get rid of the getter and setter (For example, by using Delegate instead), or make the Resources inner class public.要么摆脱 getter 和 setter(例如,改用 Delegate),要么公开 Resources 内部类。

Let's take a step back: What are you trying to accomplish?让我们退后一步:你想要完成什么? For example, if you don't want anybody to use that inner Resources class without the outer's knowledge, that's easily doable: Just make a private constructor in Resources, and, voila.例如,如果您不希望任何人在外部不知情的情况下使用该内部 Resources 类,这很容易做到:只需在 Resources 中创建一个私有构造函数,然后,瞧。 Now nobody can make instances except your outer.现在除了你的外层没有人可以制造实例。

To keep Resources private, you can delegate the setter method eg:为了保持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)
    }
}

Or you can use reflection: Set private field value with reflection或者您可以使用反射: Set private field value with reflection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM