English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to access private methods and properties of classes in Java.
To understand this example, you should be familiar with the followingJava ProgrammingTopic:
class Test { //Private variable private int age; private String name; // Initialize age public void setAge(int age) { this.age = age; } // Initialize name public void setName(String name) {}} this.name = name; } // Access age public int getAge() { return this.age; } // Access name public String getName() { return this.name; } } class Main { public static void main(String[] args) { //Create a Test object Test test = new Test(); // Set the value of the private variable test.setAge(24); test.setName("w3codebox"); //Get the value of the private variable System.out.println("Age: " + test.getAge()); System.out.println("Name: " + test.getName()); } }
Output Result
Age: 24 Name: w3codebox
In the above example, we have private variables named age and name. Here, we try to access private variables from another class named Main.
We have used getter and setter methods to access private variables. Here,
setter methods - setAge() and setName() initialize private variables
getter methods - getAge() and getName() return the values of private variables
import java.lang.reflect.*; class Test { //Private variable private String name; //Private method private void display() { System.out.println("The name is " + name); } } class Main { public static void main(String[] args) { try { //Create a Test object Test test = new Test(); //Create an object named obj Class obj = test.getClass(); //Access private variable Field field = obj.getDeclaredField("name"); // Make the private field accessible field.setAccessible(true); //Set the value of the field field.set(test, "w3codebox"); //Get the value of the field //And convert it to a string String value = (String)field.get(test); System.out.println("Name: " + value); //Access private method Method[] methods = obj.getDeclaredMethods(); System.out.println("Method Name: ", + methods[0].getName()); int modifier = methods[0].getModifiers(); System.out.println("Access Modifier: ", + Modifier.toString(modifier)); } catch(Exception e) { e.printStackTrace(); } } }
Output Result
Name: w3codebox Method Name: display Access Modifier: private
In this example, we have a private field named name and a private method named display(). Here, we use reflection to access the private field and method of the class Test.
To understand reflection, please visitJava Reflection (Reflection).