代码之家  ›  专栏  ›  技术社区  ›  Adi Sembiring

如何在不使用getter方法的情况下获取对象的所有实例变量?

  •  0
  • Adi Sembiring  · 技术社区  · 15 年前

    我有一节POJO课

    Class Book {
    private String id;
    private String title;
    
    Public Book() {
    }
    
    //implement setter and getter
    ..............
    
    }
    
    main() {
    Book book = new Book();
    book.setId(1);
    book.setTitle("new moon");
    
    }
    

    我希望结果变成->1,“新月” 不使用getter方法,所以我可以转换另一个POJO对象。


    澄清:

    我有2节课

    Book {
    String id;
    String title;
    
    //constructor
    
    //setter
    }
    
    Student {
        String id;
        String name;
    
        //cuonstructor
    
        //setter
    }
    
    main() {
    Book book = new Book();
    book.setId(1);
    book.setTitle("new moon");
    
    Student student = new Student();
    student.setId(1);
    student.setName("andrew");
    
    //suppose i have BeanUtil object to get all instance varable value and class meta data
    BeanUtil.getMetadata(book, Book.class);
    //output is
    //id, title
    
    //suppose i have BeanUtil object to get all instance varable value and class meta data
    BeanUtil.getMetadata(student, Students.class);
    //output is
    //id, name
    
    BeanUtil.getInstanceVariableValue(student, Student.class);
    //output
    //1, andrew
    
    BeanUtil.getInstanceVariableValue(book, Book.class);
    //output
    //1, new moon
    }
    
    6 回复  |  直到 13 年前
        1
  •  3
  •   MattMcKnight    15 年前

    我通常使用 PropertyUtils 它是 BeanUtils .

    //get all of the properties for a POJO
    descriptors = PropertyUtils.getPropertyDescriptors(book);
    //go through all values
    Object value = null;
    for ( int i = 0; i < descriptors.length; i++ ) {
         value = PropertyUtils.getSimpleProperty(bean, descriptors[i].getName())
     }         
    //copy properties from POJO to POJO
    PropertyUtils.copyProperties(fromBook, toBook);
    
        2
  •  1
  •   Stephen C    15 年前

    如果您想获得一个Book实例的所有属性的值,可以使用反射来实现。然而,这将需要大量的代码,而且成本高昂。更好的方法是(IMO)简单地实现 getAllValues() 方法:

    public Object[] getAllValues() {
        return new Object[]{this.id, this.title};
    }
    

        3
  •  1
  •   Droo    15 年前

    听起来像是你项目的重点(我假设是一个家庭作业项目?)是为了学习 Reflections

        4
  •  1
  •   martinatime    9 年前

    这个怎么样:

    public static String getMetadata(Class input) {
      StringBuffer result = new StringBuffer();
      // this will get all fields declared by the input class
      Field[] fields = input.getDeclaredFields();
      for (int i=0; i<fields.length; i++) {
        if (i > 0) {
          result.append(", ");
        }
        field[i].setAccessible(true);
        result.append(field[i].getName());
      }
    }
    
    public static String getInstanceVariableValue(Object input) {
      StringBuffer result = new StringBuffer();
      // this will get all fields declared by the input object
      Field[] fields = input.getClass().getDeclaredFields();
      for (int i=0; i<fields.length; i++) {
        if (i > 0) {
          result.append(", ");
        }
        fields[i].setAccessible(true);
        result.append(fields[i].get(input));
      }
        return result;
    }
    

    我没有试图编译或运行这个,所以让我知道它是如何进行的

        5
  •  0
  •   Doug Paul aleemb    15 年前

    像迈克尔一样,我不确定我是否完全理解你的问题。听起来您希望能够在给定包含其标题的字符串的情况下获取Book对象。假设您已如上所述声明了Book类,请尝试以下操作:

    public class Book {
        private String id;
        private String title;
    
        public Book(String id, String title) {
            this.id = id;
            this.title = title;
        }
    
        // Setters and getters...
    
    }
    
    public class Library {
        private Map<String, Book> booksByTitle = new HashMap<String, Book>();
    
        public Library() {
        }
    
        public void addBook(Book book) {
            this.booksByTitle.put(book.getTitle(), book);
        }
    
        public Book getBookByTitle(String title) {
            // Returns null if no matching entry is found in the map.
            return this.booksByTitle.get(title);
        }
    
        public static void main(String args[]) {
            Library myLibrary = new Library();
    
            myLibrary.addBook(new Book("1", "new moon"));
            myLibrary.addBook(new Book("2", "fight club"));
    
            Book book = myLibrary.getBookByTitle("new moon");
    
            if (book == null) {
                // A book by that title is not in the library
            }
        }
    }
    
        6
  •  0
  •   martinatime    15 年前

    我认为adisembiring要问的是如何在POJO中获取值,而不调用每个实例变量的单独getter。有一种方法可以使用反射来实现这一点。 Here