URL87
URL87

Reputation: 11022

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 ?

Upvotes: 0

Views: 2414

Answers (1)

Bozho
Bozho

Reputation: 597234

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.

Upvotes: 4

Related Questions