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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1864300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:23:07  来源:igfitidea点击:

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

javareflectioninstance-variables

提问by Adi Sembiring

I have POJO class

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

}

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.

如何在不使用getter方法的情况下获取书籍对象的所有实例变量我希望结果变为-> 1,“新月”,以便我可以转换另一个POJO对象。



Clarification:

澄清:

I have 2 classes

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

回答by Doug Paul

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:

像迈克尔一样,我不确定我是否完全理解你的问题。听起来您希望能够在给定包含其标题的字符串的情况下获取 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
        }
    }
}

回答by martinatime

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. Hereis an article on how to create toString() methods and starting with Example #2 it uses the Reflection API to dynamically determine what to output.

我认为 adisembiring 所问的是如何在不为每个实例变量调用单独的 getter 的情况下获取他的 POJO 中的值。有一种方法可以使用反射来做到这一点。是一篇关于如何创建 toString() 方法的文章,从示例 #2 开始,它使用反射 API 来动态确定要输出的内容。

回答by Stephen C

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:

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

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

或者更好的是,让它填充并返回 Map 或 Properties 对象。我想这取决于您的用例哪个更好。(虽然我很难理解为什么你想要数组/列表中所有属性的值......)

回答by MattMcKnight

I generally use PropertyUtilswhich is part of BeanUtils.

我通常使用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);

回答by martinatime

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

我没有尝试编译或运行它,所以让我知道它是怎么回事

回答by Droo

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

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