我试图在通过课程作为对象到函数后访问部门的私有字段。系是课程中的一个私有变量。解决方案必须是通用的,因为这是一个反思练习。在运行时,存储对象函数不知道传递的是哪种类型的对象,所以也不能使用类型强制转换。这是部门类:
public class Department{
private String departmentName;
private Teacher departmentHOD;
}
这是课程:
public class Course {
private String courseNumber;
private String semesterName;
private String courseName;
private Department offeringDepartment;
private Teacher[] courseInstructors;
private int sectionNumbers;
}
在main I传递过程中的函数void storeObject(Object o):
void storeObject(Object o)
{
//in this function i need to extract all possible primitive datatype objects and save them in a data base
Class classForStorage = o.getClass();
Field[] publicFields = classForStorage.getDeclaredFields();//.getFields()
for (int i = 0; i < publicFields.length; i++)
{ // making private ones accessible
publicFields[i].setAccessible(true);
//Getting name and type of all attributes in the class one by one
String fieldName = publicFields[i].getName();
Class typeClass = publicFields[i].getType();
String fieldType = typeClass.getName();
......//after this i access values by datatype and store in sql
//but it only works for primitive data types
}
我不能访问departname使用类似:
publicFields[i].getType().getDeclaredFields()[0].setAccessible(true);
value =(String)publicFields[i].getType().getDeclaredFields()[0].get(obj);
这给了我非法访问异常
如何从courseInstructor数组中获取值
你想太多了。
void printObject( Object o ) {
for ( Field fld : o.getClass().getDeclaredFields() ) {
fld.setAccessible( true );
System.out.println( fld.get( o ) );
}
}
如果您需要您的方法在字段是数组时表现不同,请使用isArray
。
void printObject( Object o ) {
for ( Field fld : o.getClass().getDeclaredFields() ) {
fld.setAccessible( true );
Object oFldVal = fld.get( o );
if ( fld.getType().isArray() ) {
int iLen = Arrays.getLength( oFldVal );
for ( int i = 0; i < iLen; ++i ) {
printObject( Arrays.get( oFldVal, i ) );
}
} else {
System.println( oFldVal );
}
}
}
Edit: "via reflection"在此答案发布后被添加到问题标题中。如果解决方案必须使用反射,则此答案不适用。
你寻找的通用解是:
public class Course {
private String courseNumber;
private String semesterName;
private String courseName;
private Department offeringDepartment;
private Teacher[] courseInstructors;
private int sectionNumbers;
//add a getter to Course
public Department getDepartment() {
return offeringDepartment
}
}
检索部门使用
Course course = new Course();
Department department = course.getDepartment();
如果'o'对象是'Course'的一个实例,你可以:
//cast object to Course and use getter
((Course)o).getDepartment();