Sameer Sarmah
Sameer Sarmah

Reputation: 1052

Access members of a non public class from outside the package using java reflection

There is a non-public class A in package1.I want to access the members of this class from another class B in package2. I have made an instance of class A using the constructor.how would I access the fields and methods in class A?

package package1;
class A {
    Integer i;
}

package package2;
class B {
    public void accessClassA() {

        Class aClass = Class.forName("package1.A");
        Constructor<?> con = aClass.getDeclaredConstructor();
        con.setAccessible(true);
        //code to access fields of class A

    }
}

Upvotes: 2

Views: 2509

Answers (1)

Sameer Sarmah
Sameer Sarmah

Reputation: 1052

Class aClass = Class.forName("package1.A");
Constructor<?> con = aClass.getDeclaredConstructor();
con.setAccessible(true);
Object instance = con.newInstance();
Field intField = aClass.getDeclaredField("i");
intField.setAccessible(true);
Integer i = (Integer)intField.get(instance);

Upvotes: 2

Related Questions