Method类代表某个类中所有方法的集合(类),包括静态方法
实例1.
String st1 = "abc";
Method methodCharAt = String.class.getMethod("charAt",int.class); //methodCharAt ---->对应String类里的charAt()方法
System.out.println(methodCharAt.invoke(st1, 2)); //methodCharAt并不能直接调用,而是通过对象(str1)来调用,若invoke(null,3),invoke的第一个参数为空,则表示此方法是该类中的静态方法
实例2.
//定义另一个有main方法的类
class TestArguments{
public static void main(String [] args){
for(String arg:args){
System.out.println(arg);
}
}
/
//若想调用上一个类中的main
public class ReflectTest {
public static void main(String[] args) throws Exception {
//TestArguments.main(new String[]{"111","333","3444"});
}
}
//使用反射方法调用main
public class ReflectTest {
public static void main(String[] args) throws Exception {
String startClassName = args[0]; //定义一个string接收传进的参数,一个类名,获得该类下的main方法,然后传参执行
Method mainMethod = Class.forName(startClassName).getMethod("main", String[].class);
mainMethod.invoke(null, (Object)new String[]{"111","333","3444"});
}
}
反射 --- 成员方法Method类的反射
最新推荐文章于 2022-06-23 11:52:35 发布