java映射
虚拟机通过得到类的字节码文件,从而创建对象。在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 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】博客园携手 AI 驱动开发工具商 Chat2DB 推出联合终身会员
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步