You can invoke private method with reflection. Modifying the last bit of the posted code:

Method method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);

There are a couple of caveats. First, getDeclaredMethod will only find method declared in the current Class, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager can prevent use of the setAccessible method. So, it may need to run as a PrivilegedAction (using AccessController or Subject).

Answer from erickson on Stack Overflow
🌐
Jenkov
jenkov.com › tutorials › java-reflection › private-fields-and-methods.html
Java Reflection - Private Fields and Methods
April 9, 2018 - This code example will print out the text "returnValue = The Private Value", which is the value returned by the method getPrivateString() when invoked on the PrivateObject instance created at the beginning of the code sample.
🌐
Baeldung
baeldung.com › home › java › core java › invoking a private method in java
Invoking a Private Method in Java | Baeldung
May 29, 2025 - Using reflection to bypass function visibility comes with some risks and may not even be possible. We ought to consider: Whether the Java Security Manager will allow this in our runtime · Whether the function we’re calling, without compile-time checking, will continue to exist for us to call in the future · Refactoring our own code to make things more visible and accessible · In this article, we looked at how to access private methods using the Java Reflection API and using Spring’s ReflectionTestUtils.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-access-private-field-and-method-using-reflection-in-java
How to Access Private Field and Method Using Reflection in Java? - GeeksforGeeks
February 5, 2021 - Whereas Class.getDeclaredMethod(String methodName, Class<?>... parameterTypes) or Class.getDeclaredMethods() can be used to get private methods. Below program may not work on online IDEs like, compile and run the below program on offline IDEs only.
🌐
Blogger
javarevisited.blogspot.com › 2012 › 05 › how-to-access-private-field-and-method.html
How to access Private Field and Method Using Reflection in Java? Example Tutorial
Use getDeclaredMethods(String name, Class · .. parameter) to get the declared private method. pass all the argument types needed by method or nothing if the method doesn't accept any argument.
🌐
Wikibooks
en.wikibooks.org › wiki › Java_Programming › Reflection › Accessing_Private_Features_with_Reflection
Accessing Private Features with Reflection - Wikibooks, open books for an open world
With dp4j [dead link] it is possible to test private members without directly using the Reflection API but simply accessing them as if they were accessible from the testing method; dp4j injects the needed Reflection code at compile-time[2].
Top answer
1 of 6
76

1) How can I access the private methods and the private data members?

You can do it with a little help of the setAccessible(true) method:

class Dummy{
    private void foo(){
        System.out.println("hello foo()");
    }
    private int i = 10;
}

class Test{
    public static void main(String[] args) throws Exception {
        Dummy d = new Dummy();

        /*---  [INVOKING PRIVATE METHOD]  ---*/
        Method m = Dummy.class.getDeclaredMethod("foo");
        //m.invoke(d); // Exception java.lang.IllegalAccessException
        m.setAccessible(true);//Abracadabra
        m.invoke(d); // Now it's OK

        /*---  [GETING VALUE FROM PRIVATE FIELD]  ---*/
        Field f = Dummy.class.getDeclaredField("i");
        //System.out.println(f.get(d)); // Not accessible now
        f.setAccessible(true); // Abracadabra
        System.out.println(f.get(d)); // Now it's OK

        /*---  [SETTING VALUE OF PRIVATE FIELD]  ---*/
        Field f2 = Dummy.class.getDeclaredField("i");
        //f2.set(d,20); // Not accessible now
        f2.setAccessible(true); // Abracadabra
        f2.set(d, 20); // Now it's OK
        System.out.println(f2.get(d));
    }
}

2) Is it possible to access a local variable via reflection?

No. Local variables cannot be accessed outside of a block in which they were created (someone could say that you can assign such a variable to a field like field = localVariable; and later access such a field via reflection, but this way we will be accessing the value, not the variable).

3) Is there any way to prevent anyone from accessing private constructors, methods, and data members?

I think for constructors or methods you could use stacktrace to check if it was invoked by Reflection.
For fields I can't find a solution to prevent accessing them via reflection.

[WARNING: This is not approved by anyone. I just wrote it inspired by your question.]

class Dummy {
    private void safeMethod() {
        StackTraceElement[] st = new Exception().getStackTrace();
        // If a method was invoked by reflection, the stack trace would be similar
        // to something like this:
        /*
        java.lang.Exception
            at package1.b.Dummy.safeMethod(SomeClass.java:38)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        ->    at java.lang.reflect.Method.invoke(Method.java:601)
            at package1.b.Test.main(SomeClass.java:65)
        */
        //5th line marked by "->" is interesting one so I will try to use that info

        if (st.length > 5 &&
            st[4].getClassName().equals("java.lang.reflect.Method"))
            throw new RuntimeException("safeMethod() is accessible only by Dummy object");

        // Now normal code of method
        System.out.println("code of safe method");
    }

    // I will check if it is possible to normally use that method inside this class
    public void trySafeMethod(){
        safeMethod();
    }

    Dummy() {
        safeMethod();
    }
}

class Dummy1 extends Dummy {}

class Test {
    public static void main(String[] args) throws Exception {
        Dummy1 d1 = new Dummy1(); // safeMethod can be invoked inside a superclass constructor
        d1.trySafeMethod(); // safeMethod can be invoked inside other Dummy class methods
        System.out.println("-------------------");

        // Let's check if it is possible to invoke it via reflection
        Method m2 = Dummy.class.getDeclaredMethod("safeMethod");
        // m.invoke(d);//exception java.lang.IllegalAccessException
        m2.setAccessible(true);
        m2.invoke(d1);
    }
}

Output from Test main method:

code of safe method
code of safe method
-------------------
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at package1.b.Test.main(MyClass2.java:87)
Caused by: java.lang.RuntimeException: method safeMethod() is accessible only by Dummy object
    at package1.b.Dummy.safeMethod(MyClass2.java:54)
    ... 5 more
2 of 6
9
  1. Using the method shown in the answer you linked to: setAccessible(true), which is a method of the superclass of Field, Constructor and Method.
  2. No.
  3. No, unless the code runs in a JVM you control, where you install a security manager. But if you give someone a jar file, and he uses the classes from this jar file, he'll be able to access everything.
🌐
DEV Community
dev.to › milad-sadeghi › working-with-private-members-and-method-invocation-in-java-reflection-4cjp
Working with Private Members and Method Invocation in Java Reflection - DEV Community
June 29, 2025 - Invoking methods reflectively using Method.invoke(), including private methods. Finally, I’ll briefly talk about a small project idea — a validation framework built with reflection — to show a practical, real-world use case of these concepts. ... Up to now, we have only used "shallow reflection" Shallow reflective access is access at runtime via the core Reflection API (java.lang.reflect) without using setAccessible.
Find elsewhere
🌐
Medium
medium.com › @knoldus › accessing-private-fields-and-methods-using-reflection-27caf3e5bdd4
Accessing private fields and methods using reflection | by Knoldus Inc. | Medium
April 26, 2020 - There are libraries, which are using reflection to access private members. Scalatest, the testing tool for the Scala ecosystem has a trait PrivateMethodTester which allows you to access the private methods of a class.
🌐
Java2Blog
java2blog.com › home › core java › reflection › access private fields and methods using reflection in java
Access private fields and methods using reflection in java - Java2Blog
January 11, 2021 - ... Access private method Can you ... method object which you want to access. Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields....
🌐
W3Schools Blog
w3schools.blog › home › java reflection call or invoke private method
Java reflection call or invoke private method - W3schools.blog
June 26, 2019 - The invoke() method is used to call public method in java using reflection API. We have use getDeclaredMethod() to get private method and turn off access check to call it.
🌐
TutorialsPoint
tutorialspoint.com › Can-private-methods-of-a-class-be-accessed-from-outside-of-a-class-in-Java
Can private methods of a class be accessed from outside of a class in Java?
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); } }
🌐
Medium
medium.com › @AlexanderObregon › how-to-test-private-methods-in-java-ec1872e81911
Testing Private Methods in Java | Medium
May 24, 2024 - Retrieve the Method object corresponding to the private method using the getDeclaredMethod method. Make the method accessible by calling setAccessible(true) on the Method object. Invoke the method using the invoke method on the Method object.
🌐
w3resource
w3resource.com › java-exercises › unittest › java-unittest-exercise-8.php
Java Testing Private methods: Reflection strategy
May 23, 2025 - Write a Java program to explore strategies for testing private methods in a class. ... // ExampleClass.java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ExampleClass { private int addTwoNumbers(int a, int b) { return a + b; } // Public method that calls the private method public int performAddition(int a, int b) { return addTwoNumbers(a, b); } // Testing private method using reflection public static int testPrivateMethod(ExampleClass instance, int a, int b) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { //
🌐
YouTube
youtube.com › watch
12.6 Calling Private Method in Java Class using Reflection API - YouTube
If we want to know behavior of the class, interface of a class file, manipulation classes, fields, methods, and constructors then we can use reflection API c...
Published   June 3, 2015
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-call-private-method-from-another-class-in-java-with-help-of-reflection-api
How to call private method from another class in Java with help of Reflection API? - GeeksforGeeks
July 12, 2025 - To call the private method, we will use the following methods of Java.lang.class and Java.lang.reflect.Method · Method[] getDeclaredMethods(): This method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
🌐
Tutorjoes
tutorjoes.in › java_programming_tutorial › calling_private_method_in_java_class_using_reflection_api_in_java
Calling Private Method in Java Class using Reflection API in Java
import java.lang.reflect.Method; class ReflectDemo { private void method1() { System.out.println("Method-1 in Private"); } private void method2(String name) { System.out.println("Method-2 in Private "+name); } } public class PrivateReflectionDemo { public static void main(String[] args) throws Exception { ReflectDemo o =new ReflectDemo(); Class c=o.getClass(); Method m1=c.getDeclaredMethod("method1",null); m1.setAccessible(true); m1.invoke(o,null);//Object,parameter Method m2=c.getDeclaredMethod("method2",String.class); m2.setAccessible(true); m2.invoke(o,"Tutor Joes");//Object,parameter } }
🌐
YouTube
youtube.com › trendingcode
Java Reflection call private method Of Other Class | reflection in java | reflection api in java - YouTube
Hi Developers, In this video I have shown how we can access private method of other call through reflection provided in java.Top Playlists:Play Design Patter...
Published   April 24, 2023
Views   601