Are there any open source java reflection tools or jars?
•
Java
Are there any open source tools or jars to handle reflection in Java?
I dynamically pass the method to a class, and I want to get the return value
For example:
class Department { String name ; Employee[] employees; public void setName(String name) { this.name = name; } public String getName() { return name; } public Employee[] getEmployes() { return employees; } }
I want to print all employees to the console output, but at run time, it is as follows:
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.
Is there any reflective open source that can accommodate such things?
Solution
When I see such things, I always ring the design alarm clock
Having said that, I usually think jxpath( http://commons.apache.org/jxpath/users-guide.html )It is the most reasonable solution for this type of problem. If the problem cannot be solved in a more designed way:
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; } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码