I am trying to access private field of department after passing course as an object to function. Department is a private variable in course. The solution needs to be generic as this is a reflection exercise. this is department class:
public class Department{
private String departmentName;
private Teacher departmentHOD;
}
this is Course class:
public class Course {
private String courseNumber;
private String semesterName;
private String courseName;
private Department offeringDepartment;
private Teacher[] courseInstructors;
private int sectionNumbers;
}
in main I pass course in a function 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
}
I cant access departname using something like:
publicFields[i].getType().getDeclaredFields()[0].setAccessible(true);
value =(String)publicFields[i].getType().getDeclaredFields()[0].get(obj);
this gives me illegal access exception
On a side note how can get values from the courseInstructor array.
Aucun commentaire:
Enregistrer un commentaire