原文:http://lukaseder.wordpress.com/2011/12/29/a-neater-way-to-use-reflection-in-java/
Java的反射机制是Java一个非常强大的工具, 但是和大多数脚本语言相比, 使用起来却是有种"懒婆娘的裹脚布——又臭又长"的感觉.
比如在PHP语言中, 我们可能这样写:
在JavaScript语言中, 我们会这样写:
在Java中, 我们会这样写:
上面的代码还没有考虑到对各种异常的处理, 比如NullPointerExceptions, InvocationTargetExceptions, IllegalAccessExceptions, IllegalArgumentExceptions, SecurityExceptions. 以及对基本类型的处理. 但是大部分情况下, 这些都是不需要关心的.
为了解决这个问题, 于是有了这个工具: jOOR (Java Object Oriented Reflection).
对于这样的Java代码:
使用 jOOR的写法:
在Stack Overflow上相关的问题讨论:
http://stackoverflow.com/questions/4385003/java-reflection-open-source/8672186
另一个例子:
jOOR相关的信息, 请猛击:
http://code.google.com/p/joor/
Java的反射机制是Java一个非常强大的工具, 但是和大多数脚本语言相比, 使用起来却是有种"懒婆娘的裹脚布——又臭又长"的感觉.
比如在PHP语言中, 我们可能这样写:
- // PHP
- $method = 'my_method';
- $field = 'my_field';
- // Dynamically call a method
- $object->$method();
- // Dynamically access a field
- $object->$field;
在JavaScript语言中, 我们会这样写:
- // JavaScript
- var method = 'my_method';
- var field = 'my_field';
- // Dynamically call a function
- object[method]();
- // Dynamically access a field
- object[field];
在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);
上面的代码还没有考虑到对各种异常的处理, 比如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);
- }
使用 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 String
jOOR相关的信息, 请猛击:
http://code.google.com/p/joor/