Javaリフレクションを使用してメソッドパラメータ名を取得できますか? 質問する

Javaリフレクションを使用してメソッドパラメータ名を取得できますか? 質問する

次のようなクラスがあるとします。

public class Whatever
{
  public void aMethod(int aParam);
}

が という名前の、 型のaMethodパラメータを使用していることを知る方法はありますか?aParamint

ベストアンサー1

Java 8 では次のことができます。

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

public final class Methods {

    public static List<String> getParameterNames(Method method) {
        Parameter[] parameters = method.getParameters();
        List<String> parameterNames = new ArrayList<>();

        for (Parameter parameter : parameters) {
            if(!parameter.isNamePresent()) {
                throw new IllegalArgumentException("Parameter names are not present!");
            }

            String parameterName = parameter.getName();
            parameterNames.add(parameterName);
        }

        return parameterNames;
    }

    private Methods(){}
}

したがって、クラスに対してWhatever手動テストを実行できます。

import java.lang.reflect.Method;

public class ManualTest {
    public static void main(String[] args) {
        Method[] declaredMethods = Whatever.class.getDeclaredMethods();

        for (Method declaredMethod : declaredMethods) {
            if (declaredMethod.getName().equals("aMethod")) {
                System.out.println(Methods.getParameterNames(declaredMethod));
                break;
            }
        }
    }
}

Java 8 コンパイラに引数[aParam]を渡した場合には、これが出力されるはずです。-parameters

Maven ユーザーの場合:

<properties>
    <!-- PLUGIN VERSIONS -->
    <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>

    <!-- OTHER PROPERTIES -->
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <!-- Original answer -->
                <compilerArgument>-parameters</compilerArgument>
                <!-- Or, if you use the plugin version >= 3.6.2 -->
                <parameters>true</parameters>
                <testCompilerArgument>-parameters</testCompilerArgument>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

詳細については、次のリンクを参照してください。

  1. 公式 Java チュートリアル: メソッドパラメータの名前の取得
  2. JEP 118: 実行時のパラメータ名へのアクセス
  3. パラメータクラスのJavadoc

おすすめ記事