using getField method of getClass
Q. When I execute the below code, its always showing the message as "No such field existing" in the exception.
How to use the "getField" method?? Could some one please help me out here?
public class ExCustomer {
int cid;
String custname;
public ExCustomer(int cid, String custname) {
this.cid = cid;
this.custname = custname;
}
public int getCid() {
return cid;
}
public String getCustname() {
return custname;
}
public void setCid(int cid) {
this.cid = cid;
}
public void setCustname(String custname) {
this.custname = custname;
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
public class ExgetClass {
public static void main(String[] args)throws Exception{
ExCustomer exp = new ExCustomer(101, "Jim");
Class c = exp.getClass();
System.out.println(exp.getClass().getName() +"\n");
//** HOW TO USE THE getField method????
try {
Field f2 = c.getField(new String("custname"));
System.out.println(f2);
}catch(NoSuchFieldException e){
System.out.println("No such field existing \n");
}
//** to get the declared fields
Field[] f1 = c.getDeclaredFields();
for (Field field : f1) {
System.out.println("Fields: "+ field);
}
}
Thank you