利用jOOR簡化Java 反射使用
原文:
http://lukaseder.wordpress.com/2011/12/29/a-neater-way-to-use-reflection-in-java/
Java的反射機制是Java一個非常強大的工具, 但是和大多數腳本語言相比, 使用起來卻是有種"懶婆娘的裹腳布——又臭又長"的感覺.
比如在PHP語言中, 我們可能這樣寫:
// PHP $method = 'my_method'; $field = 'my_field';// Dynamically call a method $object->$method();
// Dynamically access a field $object->$field;</pre>
在JavaScript語言中, 我們會這樣寫:
// JavaScript var method = 'my_method'; var field = 'my_field';// Dynamically call a function objectmethod;
// Dynamically access a field object[field];</pre>
在Java中, 我們會這樣寫:
String method = "my_method"; String field = "my_field";// Dynamically call a method object.getClass().getMethod(method).invoke(object);
// Dynamically access a field object.getClass().getField(field).get(object);</pre>
上面的代碼還沒有考慮到對各種異常的處理, 比如NullPointerExceptions, InvocationTargetExceptions, IllegalAccessExceptions, IllegalArgumentExceptions, SecurityExceptions. 以及對基本類型的處理. 但是大部分情況下, 這些都是不需要關心的.
為了解決這個問題, 于是有了這個工具: jOOR (Java Object Oriented Reflection).
對于這樣的Java代碼:
// Classic example of reflection usage try { Method m1 = department.getClass().getMethod("getEmployees"); Employee employees = (Employee[]) m1.invoke(department);for (Employee employee : employees) { Method m2 = employee.getClass().getMethod("getAddress"); Address address = (Address) m2.invoke(employee);
Method m3 = address.getClass().getMethod("getStreet"); Street street = (Street) m3.invoke(address); System.out.println(street);
} }
// There are many checked exceptions that you are likely to ignore anyway catch (Exception ignore) {
// ... or maybe just wrap in your preferred runtime exception: throw new RuntimeException(e); }</pre>
使用 jOOR的寫法:
Employee[] employees = on(department).call("getEmployees").get();for (Employee employee : employees) { Street street = on(employee).call("getAddress").call("getStreet").get(); System.out.println(street); }</pre>
在Stack Overflow上相關的問題討論:
http://stackoverflow.com/questions/4385003/java-reflection-open-source/8672186
另一個例子:
String world = on("java.lang.String") // Like Class.forName() .create("Hello World") // Call the most specific matching constructor .call("substring", 6) // Call the most specific matching method .call("toString") // Call toString() .get() // Get the wrapped object, in this case a String
jOOR相關的信息, 請猛擊:
http://code.google.com/p/joor/
轉自: http://macrochen.iteye.com/blog/1347172