How to create Java POJO class dynamically?

岁酱吖の 提交于 2019-12-13 09:13:14

问题


I have seen a post in this website regarding the dynamic POJO generation. I have the similar requirement now.

I have some tables in the database. I want to have a POJO class for each table with fields and corresponding getters and setters. These classes are to be created dynamically. Once these classes are created I should use those setters and getters in other class to get and set the data and return the Java object.

I have seen BCEL, CGLIB and some other open source tools for this, but couldnt find the proper example. Can you help me?


回答1:


Have you looked at any of the ORM (Object Relational Mapping) frameworks out there that have been created for just this purpose? Hibernate or the Java EE 6 standard JPA, for instance. It sounds like you are starting down on a path of re-inventing something that is both pretty complex and very time consuming - never a good idea.

UPDATE: in response to comment

Well, I can only say that you guys are building yourselves into a world of hurt. Consider:

  1. If you rely on completely dynamic classes, you are you going to reference those classes and objects from other classes? Through reflection? And how are you going to keep track of all the created classes, their names and the names of their setters and getters?
  2. What happens when you have to restart your system? How are you going to re-create all those dynamic classes?
  3. With a completely dynamic database, how are you going to be able to do any performance optimization on it? Like indexing, for instance.

I can only strongly advise you to re-think your architecture. Dynamic datamodels are a mess to begin with, and next to impossible to maintain, optimize and debug. I've seen systems based on it and it's not pretty. IBM Lotus WCM is a prime example of data model horror. A properly designed and normalized relational model will be better in 99,99999999% of the cases.

Combining this with a harness of dynamic, run time ORM classes will be utterly impossible to maintain (and understand).



来源:https://stackoverflow.com/questions/7120748/how-to-create-java-pojo-class-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!