类名称 Reflect.Demo 28 //类名称 Reflect.Demo 29 //类名称 Reflect.Demo
3.通过Class实例化其他类的对象
1 package Reflect; 2 3 class Person{ 4 public String getName() { 5 return name; 6 } 7 public void setName(String name) { 8 this.name = name; 9 } 10 public int getAge() { 11 return age; 12 } 13 public void setAge(int age) { 14 this.age = age; 15 } 16 @Override 17 public String toString(){ 18 return "["+this.name+" "+this.age+"]"; 19 } 20 private String name; 21 private int age; 22 } 23 24 class hello{ 25 public static void main(String[] args) { 26 Class demo=null; 27 try{ 28 demo=Class.forName("Reflect.Person"); 29 }catch (Exception e) { 30 e.printStackTrace(); 31 } 32 Person per=null; 33 try { 34 per=(Person)demo.newInstance(); 35 } catch (InstantiationException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } catch (IllegalAccessException e) { 39 // TODO Auto-generated catch block 40 e.printStackTrace(); 41 } 42 per.setName("Rollen"); 43 per.setAge(20); 44 System.out.println(pe