I have following package structure and classes.
package X
Class A
private string fieldX;
protected string getFieldX(){ return fieldX};
package Y
Class B extends A
Class C extends B
I have the ClassC object and trying to get fieldX via reflection.
Class partypes[] = new Class[0];
Object arglist[] = new Object[0];
Method getContextMethod = ClassC.class.getMethod("getFieldX",partypes);
String retValue = (string) getContextMethod.invoke(classCInstance, arglist);
But I am getting NoSuchMethod exception.
I tried also reach the fieldX directly. But this time I am getting NoSuchField Exception.
Field reqField = ClassC.class.getDeclaredField("fieldX");
reqField.setAccessible(true);
Object value = reqField.get(classCInstance);
String retValue = (string) value;
What is the thing I am doing wrong? Is there a way to get this fieldX from ClassC object?
Solution: (thanks a lot vz0 for solution);
Direct access to private field:
Field reqField = ClassA.class.getDeclaredField("fieldX");
reqField.setAccessible(true);
String value = (String)reqField.get(clazzc);
Method Call;
Class partypes[] = new Class[0];
Object arglist[] = new Object[0];
Method getContextMethod = ClassA.class.getDeclaredMethod("getFieldX",partypes);
getContextMethod.setAccessible(true);
System.out.println((String)getContextMethod.invoke(clazzc, arglist));
Reflection API can make accessible its private constructor by calling setAccessible(true) on its Constructor instance and using newInstance() we can instantiate the class.
Can you access a private variable from the superclass using the super keyword within the subclass? No. Private variables are only accessible to the class members where it belongs. protected variables can be accessed from base class.
We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.
The Class.getMethod
call is for public methods only. You need to use the Class.getDeclaredMethod
call and then setting the Method.setAccessible
property to true:
Class partypes[] = new Class[0];
Object arglist[] = new Object[0];
Method getContextMethod = ClassA.class.getDeclaredMethod("getFieldX",partypes);
getContextMethod.setAccessible(true);
String retValue = (string) getContextMethod.invoke(classCInstance, arglist);
EDIT: Since the getFieldX
method is declared on ClassA
, you need to fetch the Method from ClassA and not ClassC. As opposite to getMethod
call, the getDeclaredMethod
call ignores superclasses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With