Class.forName的使用
Class.forName返回一个类,使用此方法可以获取类
首先,创建一个Student类
1 /*** 2 * This Class is for Student bean 3 * @author Young 4 * 5 */ 6 public class Student { 7 8 private int stud_Id; 9 private String stud_Name;10 private String sex;11 private String birthday;12 private String score;13 14 public int getStud_Id() {15 return stud_Id;16 }17 18 public void setStud_Id(int stud_Id) {19 this.stud_Id = stud_Id;20 }21 22 public String getStud_Name() {23 return stud_Name;24 }25 26 public void setStud_Name(String stud_Name) {27 this.stud_Name = stud_Name;28 }29 30 public String getSex() {31 return sex;32 }33 34 public void setSex(String sex) {35 this.sex = sex;36 }37 38 public String getBirthday() {39 return birthday;40 }41 42 public void setBirthday(String birthday) {43 this.birthday = birthday;44 }45 46 public String getScore() {47 return score;48 }49 50 public void setScore(String score) {51 this.score = score;52 }53 54 /**55 * This method is a constructor56 * 57 * @author Young58 * @param id59 * @param name60 * @param sex61 * @param birthday62 * @param score63 */64 public Student(int id, String name, String sex, String birthday,65 String score) {66 67 this.stud_Id = id;68 this.stud_Name = name;69 this.sex = sex;70 this.birthday = birthday;71 this.score = score;72 }73 74 public Student() {75 76 this.stud_Id = 1000200;77 this.stud_Name = "Test";78 this.sex = "Male";79 this.birthday = "2015/01/28";80 this.score ="3.3";81 }82 }
然后使用该类
Class c = Class.forName(Student.class.getCanonicalName()); Object obj=c.newInstance(); for(Method m:c.getMethods()) { System.out.println(m.getName()); if(m.getName().equals("getId")) { System.out.println(m.invoke(obj)); }
使用invoke运行该类的方法
使用getInstance方法获取一个对象
获取不带参数的对象,如果遇到带参数的对象该怎么获取?
Class c = Class.forName(Student.class.getCanonicalName()); Constructor constructor = c.getConstructor(Integer.TYPE, String.class, String.class, String.class, String.class); Object obj = constructor.newInstance(1, "Test", "Male", "2015-07-09", "80"); for (Method m : c.getMethods()) { System.out.println(m.getName()); if (m.getName().equals("getSex")) { System.out.println(m.invoke(obj)); } }
使用Constructor ,可以设置参数