Tuesday, 12 August 2014

NoSuchFieldException

Specifies that the class doesn't have a field of a specified name.

class Employee {
    String address;
    String firstName, lastName;
    int id, age;
    String phoneNum;
}

import java.lang.reflect.Field;

public class GetFields {
   public static void main(String args[]) throws Exception{
       Employee emp = new Employee();
       Class myClass = emp.getClass();
       
       Field myField = myClass.getDeclaredField("salary");
       myField.set(emp, "Krishna");
   } 
}

Above class tries to access a field 'salary' of Employee, which is not present, so NoSuchFieldException thrown.

Exception in thread "main" java.lang.NoSuchFieldException: salary
 at java.lang.Class.getField(Class.java:1690)
 at GetFields.main(GetFields.java:8)
Java Result: 1




                                                             Home

No comments:

Post a Comment