I am using reflection to get return type of method which is String.
When I invoke function I need to cast return value to String.
How can I do that without explicitly using String and instead to use returnType obtained through reflection?
Main.java
Class returnType = method2.getReturnType(); System.out.println(returnType.getName());
String hello1 = (String) method2.invoke(personObject, "Susan", 40);
String hello2 = (java.lang.Strin) method2.invoke(personObject, "Susan", 40);
String hello2 = String.class.cast(method2.invoke(personObject, "Susan", 40));
String hello2 = Class.forName("String").cast(method2.invoke(personObject, "Susan", 40));
Person.java
public class Person {
public String sayHelloTo(String name, int age) {
return "Hello " + name + ", you are " + age + " years old";
}
}