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));
The
Class.getMethodcall is for public methods only. You need to use theClass.getDeclaredMethodcall and then setting theMethod.setAccessibleproperty to true:EDIT: Since the
getFieldXmethod is declared onClassA, you need to fetch the Method from ClassA and not ClassC. As opposite togetMethodcall, thegetDeclaredMethodcall ignores superclasses.