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

发布于 2024-08-13 15:03:31 字数 1142 浏览 9 评论 0原文

我有 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 对象。


澄清:

我有两节课

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

没有心的人 2024-08-20 15:03:31

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

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);
蓝色星空 2024-08-20 15:03:31

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

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

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

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

遥远的绿洲 2024-08-20 15:03:31

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

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

强辩 2024-08-20 15:03:31

怎么样:

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

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

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

风轻花落早 2024-08-20 15:03:31

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

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
        }
    }
}
无语# 2024-08-20 15:03:31

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文