1.通过Java反射创建运行时类的对象:
1 public static void test1() throws InstantiationException, IllegalAccessException { 2 Class<Person> clazz = Person.class; 3 //本质上内部仍是调用Person类的空参构造器 4 /* 5 要想使得该方法能够正常创建运行时类的对象,需满足以下几个条件: 6 1.运行时必须提供类的空参构造器 7 2.空参的构造器的范围权限得足够(通常设置为public) 8 9 在Javabean中要求提供一个public的空参构造器,原因: 10 1.便于通过类的反射,创建运行时类的对象 11 2.便于子类继承此类时,默认调用super()时,父类有该构造器 12 */ 13 Person obj = clazz.newInstance(); 14 System.out.println(obj); 15 }
2.Java反射动态性的体现:
1 public static void test2() {//反射的动态性 2 int num = new Random().nextInt(2); 3 String classPath = ""; 4 System.out.println(num); 5 if (num == 0) { 6 classPath = "Person"; 7 } else { 8 classPath = "Dog"; 9 } 10 Object obj = null; 11 try { 12 obj = getInstance(classPath); 13 } catch (Exception e) { 14 throw new RuntimeException(e); 15 } finally { 16 System.out.println(obj); 17 } 18 } 19 20 public static Object getInstance(String classPath) throws Exception { 21 Class clazz = Class.forName(classPath); 22 return clazz.newInstance(); 23 }
原创文章,作者:254126420,如若转载,请注明出处:https://blog.ytso.com/273567.html