Reputation: 1052
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
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