Java Reflection 5 Class Metot' u Cagirmak(invoke)

Posted by dogukanhan on September 04, 2018 · 1 min read
public class Person {
  public int alfa(String a) {
    return a.length();
  }
  
  public static String beta(int a) {
    return "a+5="+(a+5);
  }
}
Person person  = new Person();
try {
  // instance method call
  Method method = person.getClass().getMethod("alfa",String.class);
  int a = (int) method.invoke(person, "dogukan");
  System.out.println(a);
  // static method call
  method = person.getClass().getMethod("beta",int.class);
  String out  = (String) method.invoke(null,4);
  System.out.println(out);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}
7
a+5=9