LoginSignup
0
0

More than 1 year has passed since last update.

Get class method parameter name from .class file at runtime

Last updated at Posted at 2021-07-04

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) {
    ...
}

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

float totalSalary(float, float)

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) {
    ...
}

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");
    }

}

By using javap to decompile generated .class file

javap -v -cp <class path> test.TestClass

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.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0