Followings provides only public fields and methods.

Class.getField(String name);
Class.getFields();
Class.getMethod(String name, Class[] parameterTypes);
Class.getMethods();

You must do two things to access the non-public fields and methods.
1. Get them as declared ones

Class.getDeclaredField(String name);
Class.getDeclaredFields();
Class.getDeclaredMethod(String name, Class[] parameterTypes);
Class.getDeclaredMethods();

2. Make setAccessible(true) on them

Otherwise this will throw  java.lang.IllegalAccessException.

Example :

Tester.java


package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import reflection.anotherPackage.GeneralTestee;

public class Tester {

public static void main(String[] args) throws Exception {
 Tester tester = new Tester();
 tester.reflect();
 }

 public void reflect() throws Exception{

 Class testeeCls = Class.forName("reflection.anotherPackage.Testee");

 Constructor testeeConstructor = testeeCls.getConstructor(null);
 GeneralTestee generalTestee = (GeneralTestee) testeeConstructor.newInstance(null);
 System.out.println("reflect().generalTestee : " + generalTestee);

 Field[] testeeFields = testeeCls.getDeclaredFields(); // This gets all a,b,c,d
// Field[] testeeFields = testeeCls.getFields(); // This gets only a
 for (int i = 0; i < testeeFields.length; i++) {
 Field testeeField = testeeFields[i];
 testeeField.setAccessible(true);
 System.out.println(testeeField.getName() + " : " + testeeField.get(generalTestee));

 }

 Method[] testeeMethods = testeeCls.getDeclaredMethods();
 for (int i = 0; i < testeeMethods.length; i++) {
 Method testeeMethod = testeeMethods[i];
 testeeMethod.setAccessible(true);
 Object retObj = testeeMethod.invoke(generalTestee, null);
 System.out.println(testeeMethod.getName() + " : " + retObj );
 }
 }
}

Testee.java


package reflection.anotherPackage;

import java.security.Permission;

public class Testee extends GeneralTestee{

 public String a = "pu_blic";
 protected String b = "pro_tected";
 String c = "de_fault";
 private String d = "pri_vate";

 public String meth_A(){
 return "Successfully read " + a + " | "+ b + " | "+ c + " | "+ d +" in a public method";
 }

 protected String meth_B(){
 return "Successfully read " + a + " | "+ b + " | "+ c + " | "+ d +" in a protected method";
 }

 String meth_C(){
 return "Successfully read " + a + " | "+ b + " | "+ c + " | "+ d +" in a default method";
 }

 private String meth_D(){
 return "Successfully read " + a + " | "+ b + " | "+ c + " | "+ d +" in a private method";
 }

}

GeneralTestee.java


package reflection.anotherPackage;

public class GeneralTestee {}

How to avoid / control this private access in reflection

– Will be discussed with Java Reflection 3 – SecurityManager –

Advertisements