利用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;
// JavaScriptvar method = 'my_method';var field = 'my_field'; // Dynamically call a functionobject[method](); // Dynamically access a fieldobject[field];
String method = "my_method";String field = "my_field"; // Dynamically call a methodobject.getClass().getMethod(method).invoke(object); // Dynamically access a fieldobject.getClass().getField(field).get(object);
// Classic example of reflection usagetry { 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 anywaycatch (Exception ignore) { // ... or maybe just wrap in your preferred runtime exception: throw new RuntimeException(e);}Employee[] employees = on(department).call("getEmployees").get(); for (Employee employee : employees) { Street street = on(employee).call("getAddress").call("getStreet").get(); System.out.println(street);}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