<

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

Method Parameter Reflection support was added in Java 8. Simply put, it provides support for getting the names of parameters at runtime.

In this quick tutorial, we’ll take a look at how to access parameter names for constructors and methods at runtime – using reflection.

2. Compiler Argument 

In order to be able to get access to method name information, we must opt-in explicitly.

To do this, we specify the parameters option during compilation.

For a Maven project, we can declare this option in the pom.xml:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.1</version>
  <configuration>
    <source>1.8</source>
    <target>1.8</target>
    <compilerArgument>-parameters</compilerArgument>
  </configuration>
</plugin>

3. Example Class

We’ll use a contrived Person class with a single property called fullName to demonstrate:

public class Person {

    private String fullName;

    public Person(String fullName) {
        this.fullName = fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    // other methods
}

4. Usage

The Parameter class is new in Java 8 and has a variety of interesting methods. If the -parameters compiler option was provided, the isNamePresent() method will return true.

To access the name of a parameter, we can simply call getName():

@Test
public void whenGetConstructorParams_thenOk() 
  throws NoSuchMethodException, SecurityException {
 
    List<Parameter> parameters 
        = Arrays.asList(Person.class.getConstructor(String.class).getParameters());
    Optional<Parameter> parameter 
        = parameters.stream().filter(Parameter::isNamePresent).findFirst();
    assertThat(parameter.get().getName()).isEqualTo("fullName");
}

@Test
public void whenGetMethodParams_thenOk() 
  throws NoSuchMethodException, SecurityException {
 
    List<Parameter> parameters = Arrays.asList(
      Person.class.getMethod("setFullName", String.class).getParameters());
    Optional<Parameter> parameter= parameters.stream()
      .filter(Parameter::isNamePresent)
      .findFirst();
 
    assertThat(parameter.get().getName()).isEqualTo("fullName");
}

5. Conclusion

In this quick article, we looked at the new reflection support for parameter names that became available in Java 8.

The most obvious use case for this information is to help implement auto-complete support within editors.

As always, the source code can be found over on Github.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

avatar
  Subscribe  
Notify of