java dynamic attributes table

帅比萌擦擦* 提交于 2020-01-05 04:16:15

问题


I am developing a java application which needs a special component for dynamic attributes. The arguments are serialized (using JSON) and stored in a database and then deserialized at runtime. All attributes are displayed in a JTable with 3 columns (attribute name, attribute type and attribute value) and stored in a hashmap.

I have currently two problems to solve:

  1. The hashmap can also store objects and the objects can be set to null. And if set to null i dont know which class they belong to. How could i store objects even if they are null and known which class they belong to? Do i need to wrap each object in a class that will holds the class of the stored object?

  2. The objects are deserialized from json at runtime. The problem with this is that there are many different types of objects and i don't actually know all object types that will be stored in the hashmap. So i am looking for a way to dynamicly deserialize objects.. Is there such a way? Would i have to store the class of the object in the serialized json string?

Thanks!


回答1:


  1. Take a look to the Null Object Pattern. You can use an extra class to represent a Null instance of your type and still could contain information about itself.

  2. There is something called a Class Token, Which is the use of Class objects as keys for heterogeneous containers. Take a look to Effective Java By Joshua Bloch, Item 29. I'm not sure how this approach could work for you since you may have many instances of the same type but I leave it as a reference.




回答2:


First of all, can you motivate why you use JSON serialization for your attributes ?

This method is disadvantageous in many ways in my opinion, it can cause problems with database search and indexing, make database viewing painful and caus unnecessary code in your application. These problems can be not an issue, it depends how you want to use your attributes.

My solution for situation like these is simple table containing columns like:

  1. id - int
  2. attribute_name - varchar

And then add columns for each supported data type:

  1. string_value - varchar
  2. integer_value - int
  3. date_value - date

... and any other types you want.

This design allow for supreme performance using simple and typesafe ORM mapping without any serialization or other boilerplate. It can store values of any type, you just set correct column for attribute type, leaving all other with null. You can simulate null value by using null in all data columns. Indexing and searching also becomes a piece of cake.



来源:https://stackoverflow.com/questions/11847007/java-dynamic-attributes-table

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