標籤:java classloader 對象 反射 單元測試
轉載請註明出處:http://blog.csdn.net/lhy_ycu/article/details/45289391
前言
今天講講Java中的反射。我們常見的反射多用於JDBC中的載入驅動程式Class.forName("com.mysql.jdbc.Driver");、Struts的MVC、Hibernate中的ORM、Spring中的IOC還有一些其他架構等等。那它有什麼好處呢?它的好處就是能夠動態建立對象和編譯且能夠訪問某個類中的所有(包括私人)屬性方法及對象的屬性方法並進行調用,比較靈活,這樣也有利於降低類間的耦合度;但反射也有缺點,就是破壞了類的封裝性和對象的完整性。
執行個體說明
/** * 目標類 * * @author [*昨日重現*] [email protected] * @since version 1.0 * @datetime 2015年4月26日 下午4:50:28 */public class Student {private String name;private Integer age;/** * 無參構造並賦預設值 */public Student() {this.name = "張三";this.age = 22;}public Student(String name, Integer age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public void info() {System.out.println("做一個快樂的程式員~" + this);}private void joke() {System.out.println("開個玩笑啦。。。");}// 無參public void play() {System.out.println(this.name + " is playing...");}// 重載playpublic void play(String name) {System.out.println(this.name + " is playing xx with " + name);}/** * getClass().getName() + "@" + Integer.toHexString(hashCode()); * 推薦實體類都覆寫toString方法,方便查看日誌資訊 * * @return * @see java.lang.Object#toString() */@Overridepublic String toString() {return "Student [name=" + name + ", age=" + age + "]";}}
目標測試類別
/** * 利用反射對目標類進行測試 * * @author [*昨日重現*] [email protected] * @since version 1.0 * @datetime 2015年4月26日 下午5:14:52 */public class StudentTest {@BeforeClasspublic static void beforeClass() {System.out.println("=========在所有測試方法執行前執行--beforeClass=====\n");}/** * 1、Class.forName("package-name");2、Student.class;3、obj.getClass() * * @throws Exception */@Testpublic void testInfo() throws Exception {Class<?> c1 = Class.forName("com.leo.reflection.Student");// Class<?> c1 = Student.class;// 擷取其執行個體,newInstance()會預設調用無參構造器,因此需要目標類保留無參的構造器Student s1 = (Student) c1.newInstance();// System.out.println("s1 = " + s1.getClass().getCanonicalName());s1.info();int age = s1.getAge();String name = s1.getName();Assert.assertThat(age, Matchers.is(22));// normalAssert.assertThat(name, Matchers.is("李四"));// failure}/** * 通過類的載入器來擷取某個類 * * @throws Exception */@Testpublic void testInfo2() throws Exception {// 擷取一個類載入器ClassLoader cl = ClassLoader.getSystemClassLoader();// 載入指定的類Class<?> clazz = cl.loadClass("com.leo.reflection.Student");// System.out.println(clazz.getName());Student s1 = (Student) clazz.newInstance();s1.info();}/** * 訪問構造器 * * @throws Exception */@Testpublic void testConstruction() throws Exception {Class<?> c1 = Class.forName("com.leo.reflection.Student");// 擷取帶有指定參數列表的構造方法的Constructor對象Constructor<?> cs = c1.getDeclaredConstructor(String.class,Integer.class);Student s1 = (Student) cs.newInstance("小四", 24);s1.info();// 擷取指定類的所有構造器// Constructor<?>[] constructors = c1.getDeclaredConstructors();// for (Constructor<?> constructor : constructors) {// System.out.println("constructor = " + constructor);// }}/** * 訪問屬性(包括私人屬性) * * @throws Exception */@Testpublic void testField() throws Exception {Class<?> c1 = Class.forName("com.leo.reflection.Student");Student s1 = (Student) c1.newInstance();// 擷取某個屬性Field field = c1.getDeclaredField("name");// 該屬性設定為可訪問field.setAccessible(true);System.out.println("field = " + field + " , " + field.get(s1));// 擷取指定類的所有屬性// Field[] fields = c1.getDeclaredFields();// for (Field f : fields) {// f.setAccessible(true);// System.out.println(f.getName() + " = " + f.get(s1));// }}/** * 存取方法(包括私人方法) * * @throws Exception */@Testpublic void testMethod() throws Exception {Class<?> c1 = Class.forName("com.leo.reflection.Student");Student s1 = (Student) c1.newInstance();// 擷取某個類的指定無參方法Method m1 = c1.getDeclaredMethod("play");m1.invoke(s1);// 擷取某個類的指定含參方法Method m2 = c1.getDeclaredMethod("play", String.class);m2.invoke(s1, "錢七");System.out.println("=======================");// 擷取指定類的所有方法// Method[] methods = c1.getDeclaredMethods();// for (Method method : methods) {// method.setAccessible(true);// System.out.println(method.getName());// }// System.out.println("=======================\n");}@AfterClasspublic static void afterClass() {System.out.println("==========在所有測試方法執行後執行--afterClass=====\n");}}
總結1、所有類的對象其實都是Class的執行個體。2、Class執行個體化其他類的對象的時候,一定要保留預設的無參建構函式。 3、載入某個類的3種常用方式:a) Class.forName("類的完整路徑")、b) 類名.class、c) obj.getClass()4、反射的常用的兩步:Class<?> c1 = Class.forName("類的完整路徑"); T1 t = (T1) c1.newInstance();
Java學習系列(二十)Java物件導向之反射詳解