編輯:關於 Android 程式設計
反射(Reflection)讓執行於 JVM 中的程式能夠在執行期檢測並修改自身行為。這個概念常與內省(Introspection)混淆,兩者的差異如下:
內省:在執行期檢測某個物件的型別與其包含的屬性。
反射:在執行期檢測並修改某個物件的結構與行為。
可見內省是反射的子集。有些語言支援內省卻不支援反射,例如 C++。
內省範例——instanceof 運算子用於判斷物件是否屬於特定類別:
if (obj instanceof Dog) {
Dog d = (Dog) obj;
d.bark();
}
反射範例——Class.forName() 可依類別或介面名稱(字串或完整限定名)取得對應的 Class 物件,並會觸發類別初始化:
// 使用反射
Class c = Class.forName("classpath.and.classname");
Object dog = c.newInstance();
Method m = c.getDeclaredMethod("bark", new Class[0]);
m.invoke(dog);
在 Java 中,反射其實更接近內省,因為你無法改變一個物件的結構。雖然部分 API 能調整方法與屬性的可見性,卻無法修改結構本身。
反射能讓我們:在執行期檢測物件型別、動態建立某類別的物件、列舉類別的屬性與方法、任意呼叫物件方法、調整建構子/方法/屬性的可見性等等。
反射是框架設計的基石。
例如 JUnit 透過反射走訪帶有 @Test 註解的方法,並在執行單元測試時逐一呼叫。Web 框架 likewise 讓開發者在設定檔中宣告介面與類別的實作,再由反射快速動態初始化所需類別。
Spring 的設定範例:
<bean class="com.programcreek.Foo" id="someID">
<property name="someField" value="someValue" />
</bean>
容器處理該元素時,會以 Class.forName("com.programcreek.Foo") 載入類別,再用反射取得對應的 setter 方法為屬性賦值。Servlet 也採用相同機制:
<servlet>
<servlet-name>someServlet</servlet-name>
<servlet-class>com.programcreek.WhyReflectionServlet</servlet-class>
</servlet>
Java 5 引入泛型後,反射 API 也相應擴充以提供支援。由於型別擦除的存在,泛型類別中的型別參數在執行期實際上並不存在,JVM 看到的都是原始型別。為此,Java 5 修訂了 class 檔格式,新增 Signature 屬性以保存這類資訊,JVM 在執行期讀取後交由反射 API 使用。
因此,即使宣告時是 List<String>,執行期型別退化為 List,仍能透過反射取回實際的型別參數:
Field field = Pair.class.getDeclaredField("myList"); // myList 宣告為 List 型別
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType paramType = (ParameterizedType) type;
Type[] actualTypes = paramType.getActualTypeArguments();
for (Type aType : actualTypes) {
if (aType instanceof Class) {
Class clz = (Class) aType;
System.out.println(clz.getName()); // 輸出 java.lang.String
}
}
}
程式執行期間,Java 執行期系統會為所有物件維護一個「執行期型別標識」,用來追蹤該物件所屬的類別。保存這些資訊的類別即為 Class 類別。
取得 Class 物件的三種方式:
1. 呼叫 Object 的 getClass()
Object myObject = new Object();
Class myObjectClass = myObject.getClass();
2. 呼叫靜態方法 Class.forName()
String className = "java.util.Date";
Class cl = Class.forName(className);
注意:使用 Class.forName() 時必須提供類別的完整名稱,包含套件名稱。若找不到該類別,會拋出 ClassNotFoundException。
3. 使用類別字面量 T.class
Class cl1 = Date.class;
Class cl2 = int.class;
補充:可透過 getSuperclass() 取得父類別:
Object myObject = new Object();
Class myObjectClass = myObject.getSuperclass();
// 完整限定名(含套件)
Class aClass = ...;
String className = aClass.getName();
// 僅類別名稱(不含套件)
Class aClass = ...;
String className = aClass.getSimpleName();
Class aClass = ...;
int modifiers = aClass.getModifiers();
getModifiers() 回傳一個整數,以不同的位元開關描述 public / private / static 等修飾符狀態。也可搭配 Modifier 類別的判斷方法使用:
Modifier.isAbstract(int modifiers);
Modifier.isFinal(int modifiers);
Modifier.isInterface(int modifiers);
Modifier.isNative(int modifiers);
Modifier.isPrivate(int modifiers);
Modifier.isProtected(int modifiers);
Modifier.isPublic(int modifiers);
Modifier.isStatic(int modifiers);
Modifier.isStrict(int modifiers);
Modifier.isSynchronized(int modifiers);
Modifier.isTransient(int modifiers);
Modifier.isVolatile(int modifiers);
Object object = new Object();
Class cl = object.getClass();
System.out.println(cl.getPackage());
/* 輸出:package java.lang, Java Platform API Specification, version 1.7 */
Class aClass = ...;
Class[] interfaces = aClass.getInterfaces();
注意:getInterfaces() 只回傳目前類別所實作的介面,不含父類別實作的介面。
Class aClass = ...;
Constructor[] constructors = aClass.getConstructors();
回傳的陣列包含每一個宣告為 public 的建構子。
也可依參數型別取得指定建構子:
Class aClass = ...;
Constructor constructor = aClass.getConstructor(new Class[]{String.class});
若沒有符合給定參數的建構子,會拋出 NoSuchMethodException。
取得指定建構子的參數型別:
Constructor constructor = ...;
Class[] parameterTypes = constructor.getParameterTypes();
以 Constructor 物件建立實例:
Constructor constructor = ...;
Object instance = constructor.newInstance("someValue");
Class aClass = ...;
Method[] methods = aClass.getMethods();
回傳的 Method 陣列包含該類別中所有宣告為 public 的方法(含繼承而來者)。
依名稱與參數型別取得指定方法:
Class aClass = ...;
Method method = aClass.getMethod("doSomething", new Class[]{String.class});
若無法匹配,會拋出 NoSuchMethodException。
取得方法的參數型別與回傳型別:
Method method = ...;
Class[] parameterTypes = method.getParameterTypes();
Class returnType = method.getReturnType();
透過 Method 物件呼叫方法:
// 取得名為 doSomething、參數為 String 的方法
Method method = MyObject.class.getMethod("doSomething", String.class);
Object returnValue = method.invoke(instance, "parameter-value1");
Class aClass = ...;
Field[] fields = aClass.getFields();
回傳的 Field 陣列包含宣告為 public 的所有變數(含繼承而來者)。
依名稱取得指定欄位:
Class aClass = ...;
Field field = aClass.getField("someField");
若找不到對應欄位,會拋出 NoSuchFieldException。
取得欄位名稱與型別:
Field field = ...;
String fieldName = field.getName();
Class aClass = ...;
Field field = aClass.getField("someField");
Object fieldType = field.getType();
讀取與寫入欄位值:
Class aClass = MyObject.class;
Field field = aClass.getField("someField");
MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);
field.set(objectInstance, value);
Getter:名稱以 get 開頭、沒有參數、有回傳值。
Setter:名稱以 set 開頭、有一個參數。
public static void printGettersSetters(Class aClass) {
Method[] methods = aClass.getMethods();
for (Method method : methods) {
if (isGetter(method)) System.out.println("getter: " + method);
if (isSetter(method)) System.out.println("setter: " + method);
}
}
public static boolean isGetter(Method method) {
if (!method.getName().startsWith("get")) return false;
if (method.getParameterTypes().length != 0) return false;
if (void.class.equals(method.getReturnType())) return false;
return true;
}
public static boolean isSetter(Method method) {
if (!method.getName().startsWith("set")) return false;
if (method.getParameterTypes().length != 1) return false;
return true;
}
呼叫 Class.getDeclaredField(String name) 或 getDeclaredFields() 可取得私有與受保護的變數,但不包含超類別的成員;而 getField(String name) 與 getFields() 只回傳公有變數(含超類別的公有變數),無法取得私有變數。
public class PrivateObject {
private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
}
/**********************************************************************/
PrivateObject privateObject = new PrivateObject("The Private Value");
Field privateStringField = PrivateObject.class.getDeclaredField("privateString");
privateStringField.setAccessible(true);
String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);
輸出結果為 fieldValue = The Private Value。getDeclaredField() 回傳的是宣告在 PrivateObject 本身而非父類別中的欄位。
關鍵在於 setAccessible(true):它會關閉該 Field 實例的反射存取檢查,之後不論是私有、受保護或套件層級的作用域,都能從任何位置存取。但請注意,若改用一般語法存取這些超出權限範圍的成員,編譯階段仍會直接報錯。
呼叫 Class.getDeclaredMethod(String name, Class[] parameterTypes) 或 getDeclaredMethods() 可取得私有方法,不含超類別成員;getMethod() 與 getMethods() 只回傳公有方法(含繼承而來者)。
public class PrivateObject {
private String privateString = null;
public PrivateObject(String privateString) {
this.privateString = privateString;
}
private String getPrivateString() {
return this.privateString;
}
}
/*******************************************************************/
PrivateObject privateObject = new PrivateObject("The Private Value");
Method privateStringMethod =
PrivateObject.class.getDeclaredMethod("getPrivateString", null);
privateStringMethod.setAccessible(true);
String returnValue = (String) privateStringMethod.invoke(privateObject, null);
System.out.println("returnValue = " + returnValue);
輸出為 returnValue = The Private Value。getDeclaredMethod() 取得的是宣告於 PrivateObject 內部的方法。同樣地,setAccessible(true) 會解除存取檢查,讓你在任何位置都能呼叫該方法。
註解是 Java 5 的新特性,本質上是插入程式碼中的一種註記或元資料(meta data)。這些資訊可在編譯期由預編譯工具處理,也可在執行期透過反射讀取。
以下是類別註解的例子:
@MyAnnotation(name="someName", value = "Hello World")
public class TheClass {
}
註解的定義方式與介面相似:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
public String name();
public String value();
}
interface 前的 @ 符號表示這是一個註解。定義完成後即可套用於程式碼中。
兩個指示的意義:
1. @Retention(RetentionPolicy.RUNTIME) 表示該註解在執行期可透過反射存取。若未加上此指示,註解資訊不會保留到執行期,反射自然讀不到。
2. @Target(ElementType.TYPE) 表示該註解只能用在型別上(類別、介面)。也可改為 Field 或 Method;若不宣告此指示,則類別、方法與變數皆可套用。
Class aClass = TheClass.class;
Annotation[] annotations = aClass.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
也可直接指定型別取得:
Class aClass = TheClass.class;
Annotation annotation = aClass.getAnnotation(MyAnnotation.class);
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
public class TheClass {
@MyAnnotation(name="someName", value = "Hello World")
public void doSomething() {}
}
Method method = ...; // 取得方法物件
Annotation[] annotations = method.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
Method method = ...;
Annotation annotation = method.getAnnotation(MyAnnotation.class);
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
public class TheClass {
public static void doSomethingElse(
@MyAnnotation(name="aName", value="aValue") String parameter) {
}
}
Method method = ...;
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Class[] parameterTypes = method.getParameterTypes();
int i = 0;
for (Annotation[] annotations : parameterAnnotations) {
Class parameterType = parameterTypes[i++];
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("param: " + parameterType.getName());
System.out.println("name : " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
}
注意:getParameterAnnotations() 回傳二維陣列,每個方法參數各自對應一個註解陣列。
public class TheClass {
@MyAnnotation(name="someName", value = "Hello World")
public String myField = null;
}
Field field = ...;
Annotation[] annotations = field.getDeclaredAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
}
Field field = ...;
Annotation annotation = field.getAnnotation(MyAnnotation.class);
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("name: " + myAnnotation.name());
System.out.println("value: " + myAnnotation.value());
}
Android 四大組件之 Activity(六):狀態保存與恢復的真相
這一節要談的是 Activity 的狀態保存與恢復。這個主題單看條文很枯燥,動手做兩組對照實驗就一清二楚了。 準備一個實驗用的 Activity 布局放兩個按鈕和一個輸入
Android 動畫知識要點整理(12):幀動畫、視圖動畫與屬性動畫全解
動畫的分類 Android 的動畫體系可以分成三大類:幀動畫、視圖動畫(也叫補間動畫)和屬性動畫。前兩者常被合稱為補間動畫,而屬性動畫從 Android 3.0(API
Android App Widget 桌面插件開發完整教程
一、什麼是 App Widget App Widget 是嵌入在其他應用(最典型的就是桌面)中的微型應用視圖,它能接收週期性更新。你可以透過一個 AppWidgetPro
自定義 ScrollText:實作 Android 無縫循環滾動的跑馬燈文字
先看一下效果: 需求是讓一段長文字在 TextView 裡持續向左滾動,滾完之後無縫接回開頭,中間還要能穿插表情圖示。做法是自己寫一個繼承 TextView 的 S