是否有用于在 java 中处理反射的任何开源实用程序或 jar?
我正在将方法动态传递给一个类,我想获取返回值。
例如:
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.
是否有任何关于反射的开源来适应这样的事情?
最佳答案
除了使用 Apache BeanUtils 或直接使用 java.lang.reflect
API,正如其他人所建议的,您还可以使用 jOOR ,我创建它是为了减少在 Java 中使用反射的冗长。您的示例可以这样实现:
Employee[] employees = on(department).call("getEmployees").get();
for (Employee employee : employees) {
Street street = on(employee).call("getAddress").call("getStreet").get();
System.out.println(street);
}
在 Java 中使用正常反射的相同示例:
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 以更方便的方式包装了 java.lang.reflect.Proxy
功能:
interface StringProxy {
String mySubString(int beginIndex);
}
// You can easily create a proxy of a custom type to a jOOR-wrapped object
String substring = on("java.lang.String")
.create("Hello World")
.as(StringProxy.class)
.mySubString(6);
关于java - 是否有任何开源 Java 反射实用程序或 jar?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4385003/