Java Reflection
I have interface as following
public Interface A { void print();}
Inteface implementation as following
public class B implements A {
int abc =0;
public void setAbc(int abc){this.abc=abc;}
public int getAbc(return this.abc;);
void print(){
System.out.println("Hello world");
}
}
Now i assign child into interface as following
A a = new B();
using reflection i am trying to access child from parent as following
Class clazz = a.getClass()
clazz.getField("abc").set(a, new Integer(1456));
but i found no such method exception
any quick help ? i am assinging child into parent b/ci have multiple implementations which contains different properties..
The getField()
method will only find the field if it's public
. You can use the getDeclaredField
method, which will find the field if it's declared directly on the class, whether it's public
or not.
When you say getClass()
, you will get the runtime Class
(here, B
), even if the variable a
is typed as the interface A
.
Field[] declaredFields = dtoKlass.getDeclaredFields();
Do Something like this. I use getDeclaredField() to do what you're trying to achieve.
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.