利用jOOR简化Java 反射使用

原文:[url]http://lukaseder.wordpress.com/2011/12/29/a-neater-way-to-use-reflection-in-java/[/url]

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上相关的问题讨论:

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

另一个例子:

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相关的信息, 请猛击:
[url]http://code.google.com/p/joor/[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值