在 Java 中,“遍历参数”通常指以下几种情况之一。下面分别说明常见场景及写法。
public void printArgs(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
或使用索引:
public void printArgs(String... args) {
for (int i = 0; i < args.length; i++) {
System.out.println(i + ": " + args[i]);
}
}
调用:
printArgs("a", "b", "c");
main 方法的命令行参数public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
运行:
java Main arg1 arg2 arg3
Map<String, String> params = new HashMap<>();
params.put("name", "Tom");
params.put("age", "18");
for (Map.Entry<String, String> entry : params.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
如果你说的是在运行时获取并遍历方法参数名和值(反射):
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class Test {
public void foo(String name, int age) {}
public static void main(String[] args) throws Exception {
Method method = Test.class.getMethod("foo", String.class, int.class);
for (Parameter p : method.getParameters()) {
System.out.println(p.getName() + " : " + p.getType());
}
}
}
⚠️ 注意:
-parameters 选项才可见@MyAnnotation(value = "test", count = 3)
public class Demo {}
MyAnnotation ann = Demo.class.getAnnotation(MyAnnotation.class);
System.out.println(ann.value());
System.out.println(ann.count());
如果你指的是某种特定场景(例如 Spring 接口参数、HTTP 请求参数、MyBatis 参数等),可以告诉我具体用法,我可以给更针对性的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。