(As mentioned, JUnit’s and Spring’s and are great examples.)Īll important reflection related types like Class, Field, Constructor, Method, and Parameter implement the AnnotatedElement interface. They are meant to provide meta information that can be accessed at run time and then used to shape the behavior of the program. In fact, annotations are primarily targeted towards reflection. AnnotationsĪnnotations are an important part of reflection. If a static method is to be called, the instance argument will be ignored and can hence be null. The other arguments will be passed on to the called method.Ĭontinuing the openConnection example: openConnection.
An interesting detail of the latter is that the instance on which the method is to be called needs to be passed to it as the first argument. To call the underlying member they offer methods like Constructor::newInstance and Method::invoke. The instances returned by these calls are of type Constructor and Method, respectively. forName ( "" ) // `URL::openConnection` has an overload that accepts a Method openConnection = type. Here’s a method that does: Class type = Class. The getMethod("toExternalForm") call above did not specify any types because the method has no arguments. Similarly, specific methods can be accessed by calling getMethod and passing its name as well as the parameter types. To get a specific constructor, the getConstructor method can be called with the types of the constructor arguments as I have done above. That instance can be used to get fields, methods, constructors, and more. In its simple form this static method just takes a fully qualified class name and returns a Class instance for it. The gateway into the reflection API is Class::forName. Extensible applications that want to load user-provided plugins at run time are another use case. Spring and other web frameworks act similarly when looking for controllers and request mappings. Think about JUnit, for example, that wants to execute all methods that are annotated with Once it found them with a class path scan it uses getMethod and invoke to call them. Most use cases for this occur in “frameworky” environments. 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.
#Java reflection example invoke method code#
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. Using the reflection API is of course more cumbersome than writing the code directly. getMethod ( "toExternalForm" ) Object methodCallResult = method. newInstance ( "" ) // fetches the `toExternalForm` method and invokes it on // the instance that was just created Method method = type. forName ( "" ) // fetches the constructor that takes a `String` argument // and uses it to create a new instance for the given string Constructor constructor = type. 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. 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. First as plain Java code: URL url = new URL ( "" ) String urlString = url. Instead of building from the ground up I want to start with a simple example. Knowing about annotations unlocks a separate section.
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. After it you will be ready to get started or work through longer tutorials. 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. 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. To that end, Java’s reflection API offers types like Class, Field, Constructor, Method, Annotation, and others.
#Java reflection example invoke method how to#
at run time and to defer the decision on how to use them from compile time to run time. This means that the JVM enforces access control checks when invoking them.įor instance, if we try to call a private method outside its defining class or a protected method from outside a subclass or its class' package, we'll get an IllegalAccessException: = IllegalAccessException.A language that is capable of reflection, like Java is, allows developers to inspect types, methods, fields, annotations, etc. By default, not all reflected methods are accessible.