Reflection in Java

I just ruined the opportunity without getting an answer to two questions. I still do not know the answers, so looking for them:

[1] You have a Java class with private variables and getter / setter methods. How do you change such variables?

My answer: you cannot do this, private variables cannot be accessed externally. Interviewer: The correct answer is "Using reflection."

[2] What reflection methods do you use to do this? My answer: I'm not sure. Interviewer: Goodbye.

In my experience, I would (1) check if a class exists (2) create an instance (3) check if a method exists (4) call a method (5) to execute with an instance of the class. Of course, I would choose exceptions such as ClassNotFound and MethodInvocation. But is there a trick to changing private variables? And do people do this? TIA.

+5
source share
2 answers

Considering this:

You have a Java class with private variables and no getter / setter methods. How do you change such variables?

my answer will be that you don't need specific setters / getters, and you just change them in other non-specific methods. Setters / getters can be viewed in many cases as a demonstration of implementation.

To make a field available, you must call Field.setAccessible () .

This is a topic that I don’t know from the head, and should look if / when I use it (I can’t remember when I last used it). In order for the interviewer to be so hanged, this seems a little unusual.

+3
source

, , , , . , , , . , , .

, , , , , , , , , .

, . , , , .

, , , . , , , :

? - . , , , , , .

, , . , , , , getters/setter, / - .

, , : ? / "", , - .....

+1

All Articles