I have structure and package 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 a ClassC object and am trying to get fieldX through 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 get a NoSuchMethod exception.
I also tried to contact field X directly. But this time I get a NoSuchField exception.
Field reqField = ClassC.class.getDeclaredField("fieldX"); reqField.setAccessible(true); Object value = reqField.get(classCInstance); String retValue = (string) value;
What am I doing wrong? Is there any way to get this field X from a ClassC object?
Solution: (thanks a lot vz0 for the solution)
Direct access to a 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));
java reflection
huseyinarslan
source share