如果对象的字段是对象,该怎么办...有没有办法获取后一个对象的字段?

时间:2019-05-26 21:45:55

标签: java oop reflection

我正在编写一个程序,其中我需要检查对象的字段值。例如,我有一个名为Book的类,它具有String bookName,String Publisher和Author author。在“作者”中,它具有诸如字符串firstName,字符串lastName,字符串dateOfBirth的字段。我想获得作者的姓氏,并通过查看“书”中的字段将其更改为新的姓氏。另外,我必须以一种可以使用任何类型的对象的方式来实现我的方法,以便在仅更改作者的名字时也可以使用该方法。

我已经使用getDeclaredFields()遍历Book对象的字段,并且试图查找这些字段之一是否是它自己的对象。

我使用过“ instanceof”作者,但我需要找到一种方法,不需要对类名“ 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;
}

实际结果:[书名更改为“暮光之城”,作者更改为“ demo.Address@16f65612”]

预期结果应为:[bookName更改为“ Twilight”,firstName更改为“ Eli”]

1 个答案:

答案 0 :(得分:0)

您需要检查对象是否为原始数据类型和包装器类。您可以使用递归函数检查对象。请在下面找到可能满足您需求的实现类。

import java.lang.reflect.Field;
import java.util.ArrayList;

public class BookAuthor {

    public static void main(String[] args) {
        Book book = new Book();
        book.bookName = "Twiligh";
        book.publisher = "Oreilly";
        book.author = new Author();
        book.author.firstName = "";
        book.author.lastName = "Elo";
        ArrayList<String> changeList = new ArrayList<String>();
        System.out.println(makeChanges(book,changeList));
    }

    public static ArrayList<String> makeChanges(Object book,ArrayList<String> changeList) {

        try {
            Field[] bookFields = book.getClass().getDeclaredFields();
            Object object;

            for (Field field : bookFields) {
                field.setAccessible(true);
                object = field.get(book);
                if(object!=null && isWrapperAndPrimitiveType(object.getClass())) {      
                    if(field.getName().equals("bookName")) {
                        if(!object.equals("Twilight")) {
                            field.set(book, "Twilight");
                            changeList.add(field.getName()+" changed to Twilight");
                        }
                    }
                    if(field.getName().equals("lastName")) {
                        if(!object.equals("Eli")) {
                            field.set(book, "Eli");
                            changeList.add(field.getName()+" changed to Eli");
                        }
                    }
                }
                if(object!=null && !isWrapperAndPrimitiveType(object.getClass())) {                 
                    makeChanges(object,changeList);
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }

        return changeList;
    }


    public static boolean isWrapperAndPrimitiveType(Class<?> clazz) {
        return clazz.equals(Boolean.class) || 
            clazz.equals(Integer.class) ||
            clazz.equals(Character.class) ||
            clazz.equals(Byte.class) ||
            clazz.equals(Short.class) ||
            clazz.equals(Double.class) ||
            clazz.equals(Long.class) ||
            clazz.equals(Float.class)||
            clazz.equals(String.class) ||
            clazz.equals(boolean.class) || 
            clazz.equals(int.class) ||
            clazz.equals(char.class) ||
            clazz.equals(byte.class) ||
            clazz.equals(short.class) ||
            clazz.equals(double.class) ||
            clazz.equals(long.class) ||
            clazz.equals(float.class) ;
    }
} 

图书课

public class Book {
    String bookName;
    String publisher;
    Author author;
}

作者类

public class Author {
    String firstName;
    String lastName;
    String dateOfBirth;
}