简体   繁体   中英

How do I get all the instance variables of an object without using its getter methods?

I have POJO class

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");

}

How to get all instance variable of book object I want the result become -> 1, "new moon" without using the getter method, so I can convert the other POJO object.


Clarification:

I have 2 classes

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
}

I generally use PropertyUtils which is part of 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);

If you want to get the values of all attributes of a Book instance, you could do this using reflection. However, that would require a lot of code, and would be expensive. A better approach is (IMO) to simply implement a getAllValues() method:

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

or better still, have it populate and return a Map or a Properties object. I guess it depends on your use-cases which is better. (Though I'm having difficulty comprehending why you would want the values of all attributes in an array / list ...)

How about this:

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;
}

I've not tried to compile or run this so let me know how it goes

Sounds like the point of your project (I assume a homework project?) is to learn Reflections .

Like Michael, I'm not sure I understand your question fully. It sounds like you want to be able to get a Book object given a String containing its title. Assuming you've declared your Book class as above, try this:

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
        }
    }
}

I think what adisembiring is asking is how to get the values in his POJO without calling the individual getters for each instance variable. There is a way to do this using reflection. Here is an article on how to create toString() methods and starting with Example #2 it uses the Reflection API to dynamically determine what to output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM