Answers: No, No
Although it is possible to determine field types, even private fields, using the getType() method of the Field class, an attempt to access a private field will raise a java.lang.IllegalAccessException at runtime. An attempt at accessing a field using a method intended for a different type will raise a java.lang.IllegalArgumentException at runtime. The following code illustrates this.
// List the fields of a class
import java.lang.reflect.*; // for Field
class D {
private double d;
public static final int i = 37;
String s = "testing";
public D () {}
}
public class privtest {
public static void main(String args[]) {
try {
Class cls = Class.forName("D");
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
System.out.println("name = " + fld.getName());
System.out.println("decl class = " + fld.getDeclaringClass());
System.out.println("type = " + fld.getType());
int mod = fld.getModifiers();
System.out.println("modifiers = " + Modifier.toString(mod));
System.out.println("-----");
}
// Instance
Constructor ct = cls.getConstructor();
Object obj = ct.newInstance();
// The following fails at compile time with:
// d has private access in D
// ((D)obj).d = 12.4;
// The following fails at runtime with:
// java.lang.IllegalAccessException: Class privtest can not access...
fieldlist[0].setDouble(obj, 12.4);
// The following fails at runtime with:
// java.lang.IllegalArgumentException
System.out.println("Boolean:"+fieldlist[2].getBoolean(obj));
} catch (Exception e) {
System.out.println(e);
}
}
}