lundi 6 juin 2016

Java Reflection to call methods with multiple parameters

Hi I am using Java reflections to call methods and pass parameters to the methods. here is the sample code

package com.tests;
public class base
{
void method1(String username,String Pwd)
{System.out.println("method with 2 parameters "+username+" "+pwd);
}
void method2(String username,String Pwd)
{
System.out.println("\n method2 with 2 parameters "+username+" "+pwd);
    }
void method3(String username,String Pwd)
{System.out.println("\n method3 with 2 parameters "+username+" "+pwd);}
}

Piece of code used to invoke methods

    java.lang.reflect.Method method;
        try 
        {
         method= obj.getClass().getMethod(test,String.class,String.class);
         method.invoke(obj,"user1","pwd");
           } 
        catch (SecurityException e) 
        {System.out.println("SECURITY EXCEPTION :"+e);}
        catch (NoSuchMethodException e)
        {System.out.println("NoSuchMethodException EXCEPTION :"+e);}    

where test="method1" /"method2"/"method3"
obj is object of base class
the above code is throwing NOSuchmethodException





Aucun commentaire:

Enregistrer un commentaire