简体   繁体   中英

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:

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

This won't compile unless I define the Resources class as public .

Is there any other way using Lombok accessing this field while keeping Resources private?

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 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.

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. Now nobody can make instances except your outer.

To keep Resources private, you can delegate the setter method eg:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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