Results 1 to 3 of 3
- 02-02-2011, 09:05 PM #1
Member
- Join Date
- Feb 2011
- Posts
- 3
- Rep Power
- 0
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
- 02-02-2011, 09:11 PM #2
Senior Member
- Join Date
- Oct 2010
- Location
- Germany
- Posts
- 780
- Rep Power
- 4
you can use getField only if the field is public, read the API doc
"Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object. "
use getDeclaredField("custname")!
- 02-02-2011, 11:16 PM #3
Member
- Join Date
- Feb 2011
- Posts
- 3
- Rep Power
- 0
Similar Threads
-
Thread problem, calling method in run method
By majk in forum Threads and SynchronizationReplies: 4Last Post: 09-27-2010, 11:40 AM -
method not abstract, does not override actionperformed method.
By Theman in forum New To JavaReplies: 2Last Post: 03-26-2010, 05:12 PM -
ArrayLists compareTo method, equals method
By random0munky in forum New To JavaReplies: 2Last Post: 10-26-2009, 07:20 PM -
[SOLVED] java.lang.NullPointerException when reading getClass().getResourceAsStream(.
By jon80 in forum New To JavaReplies: 2Last Post: 05-31-2009, 05:03 PM -
Calling a method in a different class from within a method problem
By CirKuT in forum New To JavaReplies: 29Last Post: 09-25-2008, 07:55 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks