共計 609 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以通過反射機制獲取方法的參數值。以下是一個示例代碼:
import java.lang.reflect.Method;
public class ReflectionExample {public static void main(String[] args) {try {
Class<?> clazz = MyClass.class;
Method method = clazz.getMethod("myMethod", int.class, String.class);
Object[] parameters = new Object[]{10, "Hello"};
Object result = method.invoke(clazz.newInstance(), parameters);
System.out.println("Method result: " + result);
} catch (Exception e) {e.printStackTrace();
}
}
}
class MyClass {public String myMethod(int number, String text) {return "Number: " + number + ", Text: " + text;
}
}
在上面的示例中,我們通過反射獲取了 MyClass
類中的 myMethod
方法,并傳入參數值 10
和"Hello"
進行調用。通過反射執行方法后,我們可以獲取其返回值并打印輸出。
丸趣 TV 網 – 提供最優質的資源集合!
正文完