In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
f.setAccessible(true);
Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException

EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException

The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type
Answer from oxbow_lakes on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › reading the value of ‘private’ fields from a different class in java
Reading the Value of 'private' Fields from a Different Class in Java | Baeldung
November 13, 2025 - We can access the private fields that are objects by using the Field#get method. It is to note that the generic get method returns an Object, so we’ll need to cast it to the target type to make use of the value:
🌐
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
In order to access a private field using reflection, you need to know the name of the field than by calling getDeclaredFields(String name) you will get a java.lang.reflect.Field instance representing that field.
🌐
Programiz
programiz.com › java-programming › examples › access-private-members
Java Program to Access private members of a class
the getter methods getAge() and getName() returns the value of private variables · import java.lang.reflect.*; class Test { // private variables private String name; // private method private void display() { System.out.println("The name is " + name); } } class Main { public static void ...
🌐
W3Schools Blog
w3schools.blog › get-set-private-field-value-in-java
Java reflection get set private field value – W3schools
The get() and set() method are used to get and set public field value in java. Note: We have to turn off the java access check for field modifiers.
🌐
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 ... .setAccessible(true) on field or method object which you want to access. Class.getDeclaredField(String fieldName) or Class.getDeclaredFields() can be used to get private fields....
🌐
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.
Find elsewhere
🌐
Java: How To Do It
javahowtodoit.wordpress.com › 2014 › 08 › 28 › how-to-write-value-to-private-field-using-java-reflection
How to get and set private field using Java reflection | Java: How To Do It
September 12, 2014 - // Class declaration class MyClass1 { private String instanceField = "A"; public String getInstanceField() { return instanceField; } } // Given object MyClass1 object = new MyClass1(); // Get field instance Field field = MyClass1.class.getDeclaredField("instanceField"); field.setAccessible(true); // Suppress Java language access checking // Get value String fieldValue = (String) field.get(object); System.out.println(fieldValue); // -> A // Set value field.set(object, "B"); System.out.println(object.getInstanceField()); // -> B ·
🌐
C# Corner
c-sharpcorner.com › UploadFile › 433c33 › accessing-private-fields-and-private-methods-hacking-a-clas
Accessing Private Fields and Private Methods (Hacking a Class) in Java
October 11, 2019 - So, you use setAccessible() method, which has a default value of false, but you can set it to true. ... PrivateObject privateObject = new PrivateObject(" you Successfully access the Private data Value of a class");
🌐
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 - // Access Private Field Using Reflection in Java import java.lang.reflect.Field; // Student class declaration class Student { // private fields private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } private int getAge() { return age; } public void setAge(int age) { this.age = age; } // Override toString method to get required // output at terminal @Override public String toString() { return "Employee [nam
🌐
Programming.Guide
programming.guide › java › accessing-private-fields-of-superclass-through-reflection.html
Java: Accessing private fields of superclass through reflection | Programming.Guide
In Java, difference between default, public, protected, and private ... Executing code in comments?! ... class C { private String privateField = "Hello World"; } class SubC extends C { } class Example { public static void main(String[] args) throws Exception { SubC obj = new SubC(); Field f = SubC.class.getSuperclass().getDeclaredField("privateField"); f.setAccessible(true); String str = (String) f.get(obj); System.out.println(str); // Hello World } }
Top answer
1 of 2
1

You have do like this,

public class A {
    private B b = new B();

    class B {
        private String value = "String";
    }
}

public class ClassB {
    public static void main(String args[]) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
        A obj = new A();
        Field f = obj.getClass().getDeclaredField("b"); 
        f.setAccessible(true);
        A.B b = (B) f.get(obj);
        Field f2 = b.getClass().getDeclaredField("value");
        f2.setAccessible(true);
        String value = (String) f2.get(b);
        System.out.println(value);
    }
}

What you are missing is to setAccessible(true) to inner class field.

2 of 2
0

As a first, in your example field b is null. Is this correct? So, you try to get class of null.

As a second, in your example you use inner classes and there is a specific langugage mechanizm. You can create instance of class B only by some instance of class A. And all instances of class B has access to private field of it's parrent (class A). As in this example.

class OuterClass 
{  
    // static member 
    static int outer_x = 10; 

    // instance(non-static) member 
    int outer_y = 20; 

    // private member 
    private int outer_private = 30; 

    // inner class 
    class InnerClass 
    { 
        void display() 
        { 
            // can access static member of outer class 
            System.out.println("outer_x = " + outer_x); 

            // can also access non-static member of outer class 
            System.out.println("outer_y = " + outer_y); 

            // can also access private member of outer class 
            System.out.println("outer_private = " + outer_private); 

        } 
    } 
} 

// Driver class 
public class InnerClassDemo 
{ 
    public static void main(String[] args) 
    { 
        // accessing an inner class 
        OuterClass outerObject = new OuterClass(); 
        OuterClass.InnerClass innerObject = outerObject.new InnerClass(); 

        innerObject.display(); 

    } 
} 

May be inner classes can solves your problem? (You can read abou it here https://www.geeksforgeeks.org/nested-classes-java/) Then reflecsoin is not needed.

🌐
In Relation To
in.relation.to › 2017 › 04 › 11 › accessing-private-state-of-java-9-modules
Accessing private state of Java 9 modules - In Relation To
When the @Id annotation is given on a field of an entity, Hibernate will by default directly access fields - as opposed to calling property getters and setters - to read and write the entity’s state. Usually, such fields are private. Accessing them from outside code has never been a problem, though. The Java reflection API allows to make private members accessible and access them subsequently from other classes.
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.
🌐
LabEx
labex.io › tutorials › java-how-to-access-private-fields-434560
How to access private fields | LabEx
Learn advanced Java techniques to access private fields using reflection, exploring powerful methods to break encapsulation and manipulate hidden class members safely and effectively.
🌐
Baeldung
baeldung.com › home › java › set field value with reflection
Set Field Value With Reflection | Baeldung
January 8, 2024 - Learn how to set values of private fields in Java using the Reflection API.
🌐
Quora
quora.com › How-do-I-access-private-variables-in-Java
How to access private variables in Java - Quora
Answer (1 of 4): You can actually access all the private variables or methods of a class if the class using the java.lang.Reflect api. Here is an example: //Test class public class Test { private int id; private String name; public Test() { id=1; name="JAVA REFLECTIONS"; } public Test(i...
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-set-private-field-value-java
How to Set Private Field Value in Java: A Comprehensive Guide - CodingTechRoom
Java Reflection allows inspection of classes, interfaces, fields, and methods at runtime, even access private fields. ... You need a class with private fields to demonstrate setting values through reflection. ... Utilize the Reflection API to access and modify private fields securely. ... public class Main { public static void main(String[] args) throws Exception { Person person = new Person(); Field field = Person.class.getDeclaredField("name"); field.setAccessible(true); field.set(person, "John Doe"); System.out.println("Updated Name: " + person.getName()); } }