Need clarity on reflection API | Selenium Forum
M
Posted on 30/11/2015
I have this code in a .java file:
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Api_reflection {

public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// TODO Auto-generated method stub
String x="saymehi";
Method method=Api_reflection.class.getMethod(x,String.class);
method.invoke(method,"saymehi");

}

public static void saymehi() {
// TODO Auto-generated method stub
System.out.println("hiiiiiiiiiiiiiiiiiiiiiiii");

}

}

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Am struck in understanding this-->

Method method=Api_reflection.class.getMethod(x,String.class);
method.invoke(method,"saymehi");

---------------------------------------------------------------------------------------------------------------------------------------------------------------------

Have understood that "Method" is a class & "method" reference,"Api_reflection" is the class in which 2 lines of code is present.

Am not able to understand, class.getMethod(x,String.class);

Can you explain this section in more detail please.

Regards,
Chaitra

M
Replied on 01/12/2015

use this
[code:vsf7l1pf]package com.soapuitutorial.propertie;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Api_reflection {

public static void main(String[] args) {
// TODO Auto-generated method stub
String x = "saymehi";
Method method;
try {
method = Api_reflection.class.getMethod(x, String.class);
method.invoke(method, "saymehi1");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

public static void saymehi(String x) {
// TODO Auto-generated method stub
System.out.println("hiiiiiiiiiiiiiiiiiiiiiiii");

}

}
[/code:vsf7l1pf]