How do I read elements that are private in Java?

Asked 2 years ago, Updated 2 years ago, 72 views

I made the access restrictor of one of the elements private to design the class elements private. How can I get the value of stubIWant from the code below?

class IWasDesignedPoorly {
    private int stuffIWant;
}

IWasDesignedPoorly obj = ...;

java reflection field private

2022-09-22 22:26

1 Answers

Access to the element designated as private is only possible within the class. Therefore, it is recommended that you define a method in the class that allows access to that element.

public void setStuffIWant(int value){
    stuffIWant = value;
}
public int getStuffIWant(){
    return stuffIWant;
}

You can do it like this.


2022-09-22 22:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.