N
N
Nikita072021-08-05 09:23:48
Java
Nikita07, 2021-08-05 09:23:48

Is it possible to access private fields in JAVA?

All hello, the question is the following, there is such a class

class ImmutableUserAgent implements UserAgent {
        private final String                            userAgentString;
        private final ImmutableAgentField               userAgentStringField;
        private final Map<String, ImmutableAgentField>  allFields;
        private final List<String>                      availableFieldNamesSorted;
        private final boolean                           hasSyntaxError;
        private final boolean                           hasAmbiguity;
        private final int                               ambiguityCount;

        public ImmutableUserAgent(MutableUserAgent userAgent) {
            userAgentString = userAgent.userAgentString;
            hasSyntaxError = userAgent.hasSyntaxError;
            hasAmbiguity = userAgent.hasAmbiguity;
            ambiguityCount = userAgent.ambiguityCount;

            userAgentStringField = new ImmutableAgentField(userAgentString, 0L, false, userAgentString);

            Map<String, ImmutableAgentField> preparingAllFields = new LinkedHashMap<>(userAgent.allFields.size());


The last line, i.e.
Map<String, ImmutableAgentField> preparingAllFields = new LinkedHashMap<>(userAgent.allFields.size());


refers to the allFields field of the MutableUserAgent class. The
610b83a4b6564155645399.png

question is, how is this possible, is it referring to the private field, is this possible in Java or am I not understanding something?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
J3nQa, 2021-08-05
@J3nQa

Through reflection
https://javarush.ru/groups/posts/513-reflection-ap...

B
BorLaze, 2021-08-05
@BorLaze

Both classes (ImmutableUserAgent and MutableUserAgent) are nested in the UserAgent interface. And nested classes "see through each other".
For example, this also works:

public class C0 {

    class C1 {
        private String s;

        class C3 {
            private String s;
        }
    }

    class C2 {
        public C2(C1.C3 c3) {
            System.out.println(c3.s);
        }
    }

}

Why - do not ask :-) "So it happened historically" :-)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question