利用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;
在JavaScript语言中, 我们会这样写:
// JavaScriptvar method = 'my_method';var field = 'my_field'; // Dynamically call a functionobject[method](); // Dynamically access a fieldobject[field];
在Java中, 我们会这样写:
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);
上面的代码还没有考虑到对各种异常的处理, 比如NullPointerExceptions, InvocationTargetExceptions, IllegalAccessExceptions, IllegalArgumentExceptions, SecurityExceptions. 以及对基本类型的处理. 但是大部分情况下, 这些都是不需要关心的.
为了解决这个问题, 于是有了这个工具: jOOR (Java Object Oriented Reflection).
对于这样的Java代码:
// 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);}使用 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);}在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 StringjOOR相关的信息, 请猛击:
http://code.google.com/p/joor/ 1 楼 feikiss 2012-02-04 我试了下,这个工具的确很方便。谢谢分享~~ 2 楼 yangbobestone 2012-02-10 这个工具是比Java的反射机制要方便,不错。。。。 3 楼 huangfoxAgain 2012-02-25 这个工具不错!