有没有任何开源工具或jar来处理
java中的反射?
例如:
class Department { String name ; Employee[] employees; public void setName(String name) { this.name = name; } public String getName() { return name; } public Employee[] getEmployes() { return employees; } }
我想打印所有的员工到控制台输出,而是在运行时如下所示:
Department dept = new Department(); // add employees.. getEmployeeNames(dept,"getEmployees.getAddress.getStreet"); // So the user says they want employee street,but we don't know that // until run-tme.
有什么反思的开源可以容纳这样的东西吗?
解决方法
当我看到这种事情总是会响起设计闹钟.
话虽如此,我通常认为JXPath(http://commons.apache.org/jxpath/users-guide.html)对于这种类型的问题来说是最合理的解决方案,如果不能以更加设计的方式解决问题:
import org.apache.commons.jxpath.JXPathContext; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** */ public class JXPather { public static void main(String[] args) { Department d = new Department(); d.employees.add(new Employee(new Address("wherever a"))); d.employees.add(new Employee(new Address("wherever b"))); d.employees.add(new Employee(new Address("wherever c"))); d.employees.add(new Employee(new Address("wherever def"))); JXPathContext context = JXPathContext.newContext(d); // access matched xpath objects by iterating over them for (Iterator iterator = context.iterate("/employees/address/street"); iterator.hasNext();) { System.out.println(iterator.next()); } // or directly via standard xpath expressions System.out.println("street of third employee is: "+context.getValue("/employees[3]/address/street")); // supports most (or all ?) xpath expressions for (Iterator iterator = context.iterate("/employees/address/street[string-length(.) > 11]"); iterator.hasNext();) { System.out.println("street length longer than 11 c'ars:"+iterator.next()); } } static public class Department { List<Employee> employees = new ArrayList<Employee>(); public List<Employee> getEmployees() { return employees; } } static public class Employee { Address address; Employee(Address address) { this.address = address; } public Address getAddress() { return address; } } static public class Address { String street; Address(String street) { this.street = street; } public String getStreet() { return street; } } }