I'm writing a program wherein I need to check an object's field values. For example, I have a class called Book which has String bookName, String publisher, and Author author. In Author, it has fields such as String firstName, String lastName, String dateOfBirth. I want to get the author's last name and change it to a new last name by looking through the fields of the Book. Also, I have to implement my method in a way wherein any kind of object can be used so method can also be used when changing first name of just the author.
I have used getDeclaredFields() to loop through the fields of my Book object, and am trying to find if one of the fields is its own object.
I have used "instanceof" Author but I need to find a way that doesn't need my hardcoding of the class name "Author"
public ArrayList<String> makeChanges(Object book){
ArrayList<String> changeList= new ArrayList<String>;
try{
Field[] bookFields = book.getClass().getDeclaredFields();
String changes = "";
for (Field field: bookFields){
field.setAccessible(true);
if (field.getName().equals("firstName")){
if (!(field.get(book).equals("Twilight"))){
changes = field.getName() + changed to "Twilight";
changeList.add(changes);
}
if (field.get(book) instanceof Author){
List<String> authorChanges = makeChanges(field.get(book));
changes = Arrays.toString(authorChanges.toArray()).replace("[","").replace("]","");
changeList.add(changes);
}
}
catch(Exception e){
System.out.println(e.toString());
}
return changeList;
}
Actual result: [bookName changed to "Twilight", author changed to "demo.Address@16f65612"]
Expected result should be: [bookName changed to "Twilight", firstName changed to "Eli"]
Aucun commentaire:
Enregistrer un commentaire