A language that is capable of reflection, like Java is, allows developers to inspect types, methods, fields, annotations, etc. at run time and to defer the decision on how to use them from compile time to run time. To that end, Java’s reflection API offers types like Class, Field, Constructor, Method, Annotation, and others. With them it is possible to interact with types that were not known at compile time, for example to create instances of an unknown class and call methods on them.
This quick tip is intended to give you a high-level understanding of what reflection is, what it looks like in Java, and what it could be used for. After it you will be ready to get started or work through longer tutorials. To get the most out of it you should have a good understanding of how Java is structured, specifically what classes and methods are and how they relate. Knowing about annotations unlocks a separate section.
Instead of building from the ground up I want to start with a simple example. First as plain Java code:
URL url = new URL("https://sitepoint.com/java"); String urlString = url.toExternalForm(); System.out.println(urlString);
I decided at compile time (meaning, when I was writing the code) that I wanted to create an URL object, and call some method in it. Here’s how I would do the same with Java’s reflection API:
// the gateway to reflection is the `Class` instance // for the class you want to operate on Class<?> type = Class.forName("java.net.URL"); // fetches the constructor that takes a `String` argument // and uses it to create a new instance for the given string Constructor<?> constructor = type.getConstructor(String.class); Object instance = constructor.newInstance("https://sitepoint.com/java"); // fetches the `toExternalForm` method and invokes it on // the instance that was just created Method method = type.getMethod("toExternalForm"); Object methodCallResult = method.invoke(instance); System.out.println(methodCallResult);
Using the reflection API is of course more cumbersome than writing the code directly. But this way, details that used to be baked into the code (like that I use URL or which method I call) becomes just a parameter. As a consequence, instead of having to settle on URL and toExternalForm at compile time, they could be decided upon later when the program is already running.
Most use cases for this occur in “frameworky” environments. Think about JUnit, for example, that wants to execute all methods that are annotated with @Test. Once it found them with a class path scan it uses getMethod and invoke to call them. Spring and other web frameworks act similarly when looking for controllers and request mappings. Extensible applications that want to load user-provided plugins at run time are another use case.