

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Can private methods of a class be accessed from outside of a 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 Questions & Answers
- How to access the private methods of a class from outside of the class in Java?
- Are the private variables and private methods of a parent class inherited by the child class in Java?
- List methods of a class using Java Reflection
- Methods of StringBuffer class in Java.
- Methods of StringBuilder class in Java.
- Methods of StringTokenizer class in Java.
- Can a final class be subclassed in Java?
- Can a local variable's memory be accessed outside its scope in C/C++?
- How many ways can a property of a JavaScript object be accessed?
- Can a class in Java be both final and abstract?
- Can we declare a top level class as protected or private in Java?
- Methods of the Matcher class in Java Regex
- Methods of the Pattern class in Java Regex
- How many ways can get the instance of a Class class in Java?
- Methods of the Thread Class
Advertisements