- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to access the private methods of a class from outside of the class in Java?
You can access the private methods of a class using java reflection package.
Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.
Step2 − Set the method accessible by passing value true to the setAccessible() method.
Step3 − Finally, invoke the method using the invoke() method.
Example
import java.lang.reflect.Method; public class DemoTest { private void sampleMethod() { System.out.println("hello"); } } public class SampleTest { public static void main(String args[]) throws Exception { Class c = Class.forName("DemoTest"); Object obj = c.newInstance(); Method method = c.getDeclaredMethod("sampleMethod", null); method.setAccessible(true); method.invoke(obj, null); } }
- Related Articles
- Can private methods of a class be accessed from outside of a class in Java?
- Are the private variables and private methods of a parent class inherited by the child class in Java?
- How to access the members of a class from another class in Java?
- C++ Program to Access private members of a class
- How to access the object of a class without using the class name from a static context in java?
- How to access Static variable of Outer class from Static Inner class in java?
- Methods of the Matcher class in Java Regex
- Methods of the Pattern class in Java Regex
- Methods of StringBuffer class in Java.
- Methods of StringBuilder class in Java.
- Methods of StringTokenizer class in Java.
- How to hide unsupported interface methods from class in Java?
- How to access variables from enclosing class using lambda in Java?
- Methods of the Thread Class
- List methods of a class using Java Reflection

Advertisements