DEV Community

Salad Lam
Salad Lam

Posted on

Get class method parameter name from .class file at runtime

Notice

I wrote this article and was originally published on Qiita on 4 July 2021.


In the beginning

In the beginning class method parameter name is ignored by complier and only parameter type is recored into .class file. For example

float totalSalary(float hours, float hourlySalary) {
    ...
}
Enter fullscreen mode Exit fullscreen mode

You can get the following only if decompile .clsss file generated. This called method signature.

float totalSalary(float, float)
Enter fullscreen mode Exit fullscreen mode

So this is the reason why you can't define two methods like below with same method signature in one class.

float totalSalary(float hours, float hourlySalary) {
    ...
}

float totalSalary(float days, float dailySalary) {
    ...
}
Enter fullscreen mode Exit fullscreen mode

Start from Java 8

As I remember, new option "-parameters" is introduced into javac which includes class method parameter name into .class file. For example

package test;

public class TestClass {

    public static void main(String[] args) {
        System.out.println("Hello");
    }

}
Enter fullscreen mode Exit fullscreen mode

By using javap to decompile generated .class file

javap -v -cp <class path> test.TestClass
Enter fullscreen mode Exit fullscreen mode

Output is

01.png

Method parameter name is shown on MethodParameters. And you may refer to here for how to read this at runtime.

Relationsip between Spring Framework

Modern frameworks including Spring Framework are heavy using this feature. If "-parameters" option is not specified when compile source code, for example org.springframework.web.bind.annotation.PathVariable annotation of Spring MVC will not work.

If your project is managed by Maven, you can specify parameters parameter in Apache Maven Compiler plugin.

Or if your project is built on the top of spring-boot-starter-parent project, you don't need to do anything because complier parameter is included at parent POMs.

Top comments (0)