Reflection in Java

  1. Finding out about class members.
  2. Using class members.
  3. Reading annotations.

Finding out about class members

Using class members

  1. Invoke methods.
  2. Invoke constructor.
  3. Changing the value of fields.

Invoke methods

  • The program here invokes two methods first one is public void m() and the second one is public String m3(String str, int i)
  • c.getMethod("m3", String.class, Integer.TYPE)In this example with the last two arguments, we are passing arguments types. The method can have the same name but different arguments(overloading) so just a name is not enough for methods with arguments.
  • method3.invoke(obj1, "apple", 5); The second argument here is actually varargs to pass the method arguments. And if there is no argument we can pass null.

Invoke constructor

Changing the value of fields

  • The above code assigns each accessible(by access modifier) String property of the object to "java is cool"
  • getFields() is different than getDeclaredFields(). It returns only accessible public fields. If we use getDeclaredFields() and try to set values for not accessible fields, we will have a runtime exception.

Reading annotations

public enum RequestMethod {
GET, POST, PUT, DELETE
}

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store