lundi 10 août 2015

java reflection accessing private field throwing NoSuchFieldException even the field exist

I have a class with private field

public class HibernateSessionFactoryManager{
    private SessionFactory sessionFactory;
}

Now I want to do unit test of some method using the private field. So I was trying to access the private field using java reflection.

 try {
        Field field = HibernateSessionFactoryManager.class.getDeclaredField("sessionFactory");
        field.setAccessible(true);
        //field.set
        SessionFactory sessionFactory = (SessionFactory) field.get(manager);
    } catch (NoSuchFieldException e) {
        System.out.println("no such");
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

I am getting

java.lang.NoSuchFieldException: sessionFactory at java.lang.Class.getField(Class.java:1584)

I am not able to figure out what mistake im doing. Any help will be appreciated.





Aucun commentaire:

Enregistrer un commentaire