How to keep argument names of interface after compilation in Java?
Asked Answered
K

2

14

I want to keep argument names of interface methods after compilation in Java.

Below is an example.

Before compiling:

interface IFoo {
    void hello(String what);
}

After compiling using javac -g:vars IFoo.java

interface IFoo {
    void hello(String str);
}

The argument what is renamed to str.

How can I keep the argument names?

Kempis answered 19/9, 2018 at 7:58 Comment(0)
S
4

An argument or local variable has no name, only a number.

I believe the command line argument for adding local variable names is -parameters to enable access via reflection https://www.beyondjava.net/reading-java-8-method-parameter-named-reflection

It's the decompiler's job to determine/guess a variable name. I use Fernflower which does a reasonable job.

Input

import java.util.stream.Stream;

interface IFoo {
    public abstract void hello(String what);

    public static void print(String... args) {
        Stream<String> stream = Stream.of(args);
        stream.forEach(System.out::println);
    }
}

output using Fernflower

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
import java.io.PrintStream;
import java.util.function.Consumer;
import java.util.stream.Stream;

interface IFoo {
    void hello(String what);

    static void print(String... args) {
        Stream<String> stream = Stream.of(args);
        PrintStream var10001 = System.out;
        System.out.getClass();
        stream.forEach(var10001::println);
    }
}

NOTE: The System.out.getClass(); is generated by the javac compiler to test for a null value.

Singband answered 19/9, 2018 at 8:1 Comment(0)
S
4

You need to generate debugging information when compiling. This is what the Javac option -g does:

-g — Generates all debugging information, including local variables.


If you are using Maven, you can set <debug>true</debug> in the compiler plugin's configuration.

Sparkie answered 19/9, 2018 at 8:3 Comment(1)
While working like a charm for class methods and also static interface methods it does not work for non-static interface methods.Dewie

© 2022 - 2024 — McMap. All rights reserved.