vendredi 7 juin 2019

Reflection...NPE when getting field value

I have this POJO class :

  @Component
  public class ClassOne{
    public int  id;
    public String fname;
    public String lname;
    public String    code;

    super constructor
    fields constructor
    getters & setters
   }

I have this service class :

   @Service
   public  class ClassOneServiceImpl implements ClassOneService{

  public ClassOneServiceImpl{}

  @override
  public boolean addUser(String fname,String lname,String code){

    Class<?> theClass = 
    Class.forName("com.somepackage.ClassOne");
    Constructor<?> theClassConstructor = 
   theClass.getConstructor(String.class, String.class,String.class);
    ClassOne theClassObj = (ClassOne) 
   theClassConstructor.newInstance("fname","lname","code");

    Field fnameField = theClass.getDeclaredField("fname");
    Field lnameField = theClass.getDeclaredField("lname");
    Field codeField = theClass.getDeclaredField("code");

    System.out.println("Field name is " + 
    fnameField.getName());  //I get the Field's name

String fnameStr =(String) 
       fnameField.get(theClassObj);  //the NPE caused here 
String lnameStr =(String) 
       lnameField.get(theClassObj);


    System.out.println(fnameString);  //here getting null

    ...here is the code to persist the form's field data .

  }

}

Obviously the "theClassObj" is not been instantiated,since the service class has no main method ... What's my mistake & how to get the instance in this case ?

I tried place the instance from within the service class constructor..didn't work.

  java.lang.NullPointerException: null





Aucun commentaire:

Enregistrer un commentaire