user2309944
user2309944

Reputation:

NoSuchMethodException thrown when using reflection api

I am using reflection api to invoke a method from an instance of a class. everything is ok and I followed many tutorials and official oracle docs step by step but it throws NoSuchMethodException. here is my code:

// Part of the main class
    Class[] argTypes = new Class[2];
    argTypes[0] = HttpServletRequest.getClass();
    argTypes[1] = HttpServletResponse.getClass();

    Object[] args = new Object[2];
    args[0] = request;
    args[1] = response;

    try {
        Class<?> cls = Class.forName("x.xx.xxx.Default");
        Object object = cls.newInstance();
        Method method = cls.getDeclaredMethod("index", argTypes);
        method.invoke(object, args);
    } catch (Exception exception) { // for simplicity of the question, I replaced all exception types with Exception
        exception.printStackTrace();
    }

// End of the main class
    // class x.xx.xxx.Default

    public class Default {
        public void index(HttpServletRequest request, HttpServletResponse response) {
            try {
                PrintWriter writer = response.getWriter();
                writer.println("Welcome");
            } catch (IOException exception) {
                System.err.println(exception);
            }
        }
    }

and this is the description of exception which I gave when the exception happens

java.lang.NoSuchMethodException: x.xx.xxx.Default.index(org.apache.catalina.connector.RequestFacade, org.apache.catalina.connector.ResponseFacade)

Upvotes: 1

Views: 141

Answers (3)

anothernoc
anothernoc

Reputation: 177

You are trying to invoke a method of the clas "x.xx.xxx.Default" (is that a valid class name?) on a on object of type 'Object'.

I would try this:

YourClassType object = (YourClassType) cls.newInstance();

Or something like that. i cant do a good lookup right now, but i am positive that you are trying to invoke a method from a certain type on a object of type 'Object', which doesnt know that particular method.

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

I believe you need to pass the static class and not the class at runtime.

Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.class;
argTypes[1] = HttpServletResponse.class;

Upvotes: 2

Guillaume Darmont
Guillaume Darmont

Reputation: 5018

In the following code :

Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.getClass();
argTypes[1] = HttpServletResponse.getClass();

HttpServletRequest and HttpServletResponse are variables, thus getClass() call is subject to polymorphism.

You want to write :

Class[] argTypes = new Class[2];
argTypes[0] = HttpServletRequest.class;
argTypes[1] = HttpServletResponse.class;

Upvotes: 1

Related Questions