虚拟机通过得到类的字节码文件,从而创建对象。在java代码中可用Class类中的方法进行实现,
1 package javase; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.InvocationTargetException; 5 6 public class ReflextDemo { 7 8 public static void method2() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 9 10 String name = "test.Person";//把类名的路径存到字符串 11 Class clazz = Class.forName(name);//通过路径拿到字节码文件,创建对象 12 Constructor<Person> con = clazz.getConstructor(String.class,int.class);//获取构造器 13 Object obj = con.newInstance("小强",10);//创建实例 14 15 } 16 17 public static void method1() throws ClassNotFoundException, InstantiationException, IllegalAccessException { 18 19 String name = "test.Person";//把类名的路径存到字符串 20 Class clazz = Class.forName(name);//通过路径拿到字节码文件,创建对象 21 Object obj = clazz.newInstance();//创建实例 22 23 } 24 25 public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 26 27 method2(); 28 29 } 30 31 }