Results 1 to 3 of 3
  1. #1
    jdigger is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Question 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

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    6

    Default

    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")!

  3. #3
    jdigger is offline Member
    Join Date
    Feb 2011
    Posts
    3
    Rep Power
    0

    Default

    eRaa,

    Thank you very much for the clarification, I didn't observed that, Will make sure.

Similar Threads

  1. Thread problem, calling method in run method
    By majk in forum Threads and Synchronization
    Replies: 4
    Last Post: 09-27-2010, 11:40 AM
  2. Replies: 2
    Last Post: 03-26-2010, 05:12 PM
  3. ArrayLists compareTo method, equals method
    By random0munky in forum New To Java
    Replies: 2
    Last Post: 10-26-2009, 07:20 PM
  4. Replies: 2
    Last Post: 05-31-2009, 05:03 PM
  5. Replies: 29
    Last Post: 09-25-2008, 07:55 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •