利用jOOR简化Java 反射使用

来源:互联网 发布:ubuntu 装在ntfs 编辑:程序博客网 时间:2024/06/15 11:47
原文:http://lukaseder.wordpress.com/2011/12/29/a-neater-way-to-use-reflection-in-java/ 

Java的反射机制是Java一个非常强大的工具, 但是和大多数脚本语言相比, 使用起来却是有种"懒婆娘的裹脚布——又臭又长"的感觉.  

比如在PHP语言中, 我们可能这样写: 

Php代码  收藏代码
  1. // PHP  
  2. $method = 'my_method';  
  3. $field  = 'my_field';  
  4.    
  5. // Dynamically call a method  
  6. $object->$method();  
  7.    
  8. // Dynamically access a field  
  9. $object->$field;  


在JavaScript语言中, 我们会这样写: 
Js代码  收藏代码
  1. // JavaScript  
  2. var method   = 'my_method';  
  3. var field    = 'my_field';  
  4.    
  5. // Dynamically call a function  
  6. object[method]();  
  7.    
  8. // Dynamically access a field  
  9. object[field];  

在Java中, 我们会这样写: 

Java代码  收藏代码
  1. String method = "my_method";  
  2. String field  = "my_field";  
  3.    
  4. // Dynamically call a method  
  5. object.getClass().getMethod(method).invoke(object);  
  6.    
  7. // Dynamically access a field  
  8. object.getClass().getField(field).get(object);  


上面的代码还没有考虑到对各种异常的处理, 比如NullPointerExceptions, InvocationTargetExceptions, IllegalAccessExceptions, IllegalArgumentExceptions, SecurityExceptions. 以及对基本类型的处理. 但是大部分情况下, 这些都是不需要关心的. 

为了解决这个问题, 于是有了这个工具: jOOR (Java Object Oriented Reflection). 

对于这样的Java代码: 
Java代码  收藏代码
  1. // Classic example of reflection usage  
  2. try {  
  3.   Method m1 = department.getClass().getMethod("getEmployees");  
  4.   Employee employees = (Employee[]) m1.invoke(department);  
  5.    
  6.   for (Employee employee : employees) {  
  7.     Method m2 = employee.getClass().getMethod("getAddress");  
  8.     Address address = (Address) m2.invoke(employee);  
  9.    
  10.     Method m3 = address.getClass().getMethod("getStreet");  
  11.     Street street = (Street) m3.invoke(address);  
  12.    
  13.     System.out.println(street);  
  14.   }  
  15. }  
  16.    
  17. // There are many checked exceptions that you are likely to ignore anyway  
  18. catch (Exception ignore) {  
  19.    
  20.   // ... or maybe just wrap in your preferred runtime exception:  
  21.   throw new RuntimeException(e);  
  22. }  


使用 jOOR的写法: 

Java代码  收藏代码
  1. Employee[] employees = on(department).call("getEmployees").get();  
  2.    
  3. for (Employee employee : employees) {  
  4.   Street street = on(employee).call("getAddress").call("getStreet").get();  
  5.   System.out.println(street);  
  6. }  


在Stack Overflow上相关的问题讨论: 

http://stackoverflow.com/questions/4385003/java-reflection-open-source/8672186 

另一个例子: 

Java代码  收藏代码
  1. String world =  
  2. on("java.lang.String")  // Like Class.forName()  
  3.  .create("Hello World"// Call the most specific matching constructor  
  4.  .call("substring"6)  // Call the most specific matching method  
  5.  .call("toString")      // Call toString()  
  6.  .get()                 // Get the wrapped object, in this case a String  


jOOR相关的信息, 请猛击: 
http://code.google.com/p/joor/