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.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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.