views:

348

answers:

6

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

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
        }
    }
}
Doug Paul
A: 

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.

martinatime
+1  A: 

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 ...)

Stephen C
+1  A: 

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);
MattMcKnight
Thanks Matt ..But it just get all properties of the object.how abut getting all instance variable value ?
adisembiring
added that to the answer
MattMcKnight
+1  A: 

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(", ");
    }
    field[i].setAccessible(true);
    result.append(field[i].get(input));
  }
}

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

martinatime
Your code will be conflicted if the access modifier of instance variable set to privatecan you give me another suggestion ?
adisembiring
@martinatime. Just a suggestion, if you want to access `private` attributes also, do `field.setAccessible(true)` before using the `field`. If you don't want the access to `private` attributes, use `getClass().getFields()`, instead of `getClass().getDeclaredFields()`.
Adeel Ansari
but *remember* that `getFields()` also returns all public fields from the superclasses!
Carlos Heuberger
I was basically taking the link that I included in my other answer and wrote up some quick code snippets as examples. I didn't try to compile or run them as I leave that as an exercise for @adisembiring. @Vinegar thanks for hints. I'll update my snippets
martinatime
A: 

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

Droo