Java Reflection 5 Class Metot’u Cagirmak(invoke)

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

 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *