This question already has an answer here:
- What is reflection and why is it useful? 16 answers
I have just started learning Java. Sorry for asking silly doubts.
First of all, what is the use of Reflection API? I heard if we have same method and variable name then we use reflection API. I am confused.
Below program 1 and program 2 brings the same output. Then why do we use that. Kindly explain program 1 line 9 and 10. Thanks for the support friends.
Program 1:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Practice {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
String x="SampleTest";
//Explain below 2 lines please
Method method=Practice.class.getMethod(x, String.class);
method.invoke(method, "Hello");
}
public static void SampleTest(String x){
System.out.println("In Sample Test--"+x);
}
}
Program 2:
public class Practice {
public static void main(String[] args){
String x="SampleTest";
SampleTest("Hello");
}
public static void SampleTest(String x){
System.out.println("In Sample Test--"+x);
}
}
Output for both the program is In Sample Test--Hello
Thanks once again
Aucun commentaire:
Enregistrer un commentaire