package xp;
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) throws Exception {
//获取类字节码对象
Class<?> cls = Test.class;
//获取方法(方法名称, 参数列表)
Method m1 = cls.getDeclaredMethod("doTest01", new Class<?>[]{String.class, Integer.class});
Method m2 = cls.getDeclaredMethod("doTest02", String[].class);
//私有方法可见
m1.setAccessible(true);
m1.setAccessible(true);
//调用方法
m1.invoke(cls.newInstance(), new Object[]{"bingo", 28});
m2.invoke(cls.newInstance(), new Object[] {new String[]{"阴阳师", "LoL", "KEEP"}});
}
private void doTest01(String name, Integer age) {
System.out.println(name+": "+age+"岁;");
}
private void doTest02(String... hobby) {
StringBuilder hobbies = new StringBuilder("{");
for (int i = 0; i < hobby.length-1; i++) {
hobbies.append(hobby[i]+",");
}
hobbies.append(hobby[hobby.length-1]+"};");
System.out.println("爱好: "+hobbies.toString());
}
}
java反射调用变长参数方法
最新推荐文章于 2022-08-18 18:44:29 发布