Statement和Expression是java对反射的封装,测试代码如下:
package com.beans;
public class User {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int compute(int n) {
return 10 * n;
}
}
package com.beans;
import java.beans.Expression;
import java.beans.Statement;
import junit.framework.TestCase;
import static java.lang.System.out;
public class TestStatement extends TestCase {
public void testStatement() {
try {
User user = new User();
Statement statement = new Statement(user, "setAge", new Object[] { 10 });
statement.execute();
out.println(user.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
public void testExpression() {
try {
User user = new User();
Expression expression = new Expression(user, "compute", new Object[] { 20 });
expression.execute();
out.println(expression.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Statement和Expression的区别:
Expression是可以获得返回值的,方法是getValue。Statement不能获得返回值。