溫馨提示×

java中method方法如何獲取參數(shù)類型

小樊
82
2024-09-29 09:27:56
欄目: 編程語言

在Java中,你可以使用反射(Reflection)來獲取方法的參數(shù)類型。以下是一個簡單的示例:

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class Main {
    public static void main(String[] args) {
        try {
            // 獲取Main類的testMethod方法
            Method method = Main.class.getDeclaredMethod("testMethod", String.class, int.class);

            // 獲取方法的參數(shù)類型
            Class<?>[] parameterTypes = method.getParameterTypes();

            // 輸出參數(shù)類型
            for (Class<?> parameterType : parameterTypes) {
                System.out.println(parameterType.getName());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public static void testMethod(String str, int num) {
        // ...
    }
}

在這個示例中,我們首先通過getDeclaredMethod方法獲取了Main類中的testMethod方法。然后,我們使用getParameterTypes方法獲取了該方法的參數(shù)類型,并將它們存儲在一個Class<?>[]數(shù)組中。最后,我們遍歷這個數(shù)組并輸出每個參數(shù)類型的名稱。

0