public class Test8
{
public static void main(String[] args)
{
try
{
Class<?> clazz = Class.forName("com.itheima.Person1");// 加载字节码文件
Person1 person = (Person1) clazz.newInstance();//创建Person实例
Method method = clazz.getMethod("printSomething");//获取方法。这里其实是两个参数,但是后面的参数是空的所以逗号也可以省略。
method.invoke(person);//在得到的person实例上调用获取到的方法。这里的invoke也是两个参数,但由于这个方法不接受参数,所以后面的可变参数里面什么也没有,所以连逗号也可以省略。但如果加逗号后面还什么也不写会报错。
} catch (Exception e)
{
e.printStackTrace();
}
}
}
class Person1
{
public void printSomething()
{
System.out.println("Hello Java!");
}
}