简体   繁体   中英

invoke a method in a servlet class

I have this servlet -

@WebServlet("/CreateNewPersonServlet")
public class CreateNewPersonServlet extends HttpServlet {
      private void saveInDB() {

            // here use the invoke ...
            String methodName = "saveManager";
            Method method = CreateNewPersonServlet.class.getMethod(
                    methodName, new Class[] {});
            method.invoke(this);

      }
      private void saveManager() {

      }

}

When the running reach to the line -

Method method = CreateNewPersonServlet.class.getMethod(
                        methodName, new Class[] {});

it throws the exception -

java.lang.NoSuchMethodException: control.CreateNewPersonServlet.saveManager()
    at java.lang.Class.getMethod(Unknown Source)

How I should write the invoke correctly ?

The method is private, you should use .getDeclaredMethod(..) , and then use setAccessible(true)

.getMethod(..) returns only public methods. But you may as well make the method public.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM