이름 그대로 접근 권한을 설정해주는 기능이다.
true와 false를 이용해서 접근권한을 설정해줄 수 있다.
getDeclareFields 메서드를 사용하면 특정 클래스 내의 멤버변수를 전부 가져올 수 있다.
Field[] carArray = car.getClass().getDeclaredFields();
참고
setAccessible(true)를 사용하면 멤버변수값을 가져오거나 수정할 수 있다.
이때 변수의 값은 Object이다.
Object value = carArray[1].get(car)
주의
car클래스에서 1번째는 position 변수이다.
position 변수의 값인 0을 가져오지만 int가 아니라 Object이다.
Car 클래스의 position 변수값을 +1하는 과정
주의 : try catch 구문에 넣어줘야 작동한다.
public class Car {
private final String name;
private int position = 0;
public Car(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
String name = "car1";
Car car = new Car(name);
try {
Field[] carArray = car.getClass().getDeclaredFields();
carArray[1].setAccessible(true);
Object value = carArray[1].get(car);
carArray[1].set(car, (int) value + 1);
carArray[1].setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}