java.lang.IllegalArgumentException: object is not an instance of declaring class when I use reflection
java, reflection
Solution
Short version: You are missing the first argument in your call to `invoke`.
Long version: You are calling
Method method = DoerDAO.class.getDeclaredMethod(requestedUser,
Dossier.class,
SessionFactory.class);
Let's say that the value of `requestedUser` is `getReviewerOneDetail`, then you'd look up the method
getReviewerOneDetail(Dossier arg0, SessionFactory arg1)
Next you call
method.invoke(dossierDetail.get(0), sessionFactory);
The JavaDoc states that invoke gets as first parameter the instance(!) of the class to call the method on and as second, third, ... parameters the actual parameters for your invocation.
So, what you actually trying to call in your code, is
dossierDetail.get(0).getReviewerOneDetail(sessionFactory);
which does neither match the method signature (1 parameter vs. 2 parameters), nor the instance type on which the method is called (`Dossier` instead of `DoerDAO`).
Because you acquire the `Method` from the `DoerDAO` class, I guess what you intended to write there, was actually:
method.invoke(doerDao, dossierDetail.get(0), sessionFactory);
This would translate to
doerDao.getReviewerOneDetail(dossierDetail.get(0), sessionFactory);
Problem
I am new to Java reflection. I tried to call one method of my `DAO` Class using reflection, and I got the below mentioned error of illegal argument exception. Below is my code. My method contains two arguments: one is Dossier bean object and another is `sessionfactory` object. I got this error when I invoke my method. I searched lot on net but did not find the proper solution. ``` public String getDossierDetail(HttpSession session,DoerDAO doerDao,SessionFactory sessionFactory,String requestedUser) throws ClassNotFoundException{ log.info("(getDossierDetail)Execution starts"); ReviewerOne reviewer = new ReviewerOne(); String message = ""; DoerDAO doerDaoInt = new DoerDAO(); try{ List<Dossier> dossierDetail = (List<Dossier>) session.getAttribute(ObjectConstant.dossierDetailBean); System.out.println("dossierDetail: "+dossierDetail.size()+"product nm: "+dossierDetail.get(0).getProductName()+"requested User: "+requestedUser); Method method = DoerDAO.class.getDeclaredMethod(requestedUser,Dossier.class,SessionFactory.class); method.invoke(dossierDetail.get(0), sessionFactory); }catch(Exception e){ e.printStackTrace(); log.error("(getDossierDetail)Error is: ",e); message = e.getLocalizedMessage(); } return message; } ``` my requestedUser value is :: getReviewerOneDetail. /** DoerDao method ********/ ``` public void getReviewerOneDetail(Dossier dossierBean,SessionFactory sessionFactory){ log.info("(getReviewerOneDetail)Execution starts."); try{ System.out.println("in reviewer one detail...."); }catch(Exception e){ e.printStackTrace(); log.error("(getReviewerOneDetail)Error is: ",e); } } ```