【发布时间】:2012-10-16 09:54:38
【问题描述】:
我正在尝试对 Cobol 系统进行建模的 Java 框架。我有一个具有许多属性的类 StudentRecord。
class StudentRecord extend BaseRecord {
...
public CobolString firstName;
public CobolString lastName;
...
}
class CobolString {
...
private String content;
public setValue(String str){
content = str;
}
}
假设我有一个 StudentRecord 类型的实例 studentA,String 中的 firstName 值为“Max”。我想使用 Java 反射将属性 firstName 更新为“John”。通常,我会这样做:
Class aClass = studentA.class;
Field field = aClass.getField("firstName");
field.set(studentA, new CobolString("John"));
因为这个框架是为 Cobol 建模的,所以它有一些奇怪的行为和要求。其中之一是我需要使用 CobolString 的 setValue() 方法为 firstName 设置新值,以确保系统正常工作。
例如:没有反射,它要求我做:
studentA.firstName.setValue("John");
使用反射,如果我这样编码,studentA 仍然有新的 firstName,但它对其他对象/方法变得陌生,无法与其他人一起工作!!!
那么我怎样才能使用 Java 反射来为 firstName 设置新值。我的意思是我如何从父对象 studentA 获取子对象 firstName,然后使用新值“John”对其调用方法“setValue”。
感谢您的帮助。
【问题讨论】:
标签: java reflection cobol