Java, access to private property through Reflection

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)); 
+8
java reflection
source share
1 answer

The call to Class.getMethod is for public methods only. You need to use the call to Class.getDeclaredMethod , and then set 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 getFieldX declared in ClassA , you need to select the method from ClassA, not ClassC. Unlike calling getMethod calling getDeclaredMethod ignores superclasses .

+12
source share

All Articles