Java classes with dynamic fields

后端 未结 5 808
孤独总比滥情好
孤独总比滥情好 2021-02-06 10:55

I\'m looking for clever ways to build dynamic Java classes, that is classes where you can add/remove fields at runtime. Usage scenario: I have an editor where users should be ab

5条回答
  •  不要未来只要你来
    2021-02-06 11:14

    So basically you're trying to create a new kind of object model with more dynamic properties, a bit like a dynamic language?

    Might be worth looking at the source code for Rhino (i.e. Javascript implemented in Java), which faces a similar challenge of implementing a dynamic type system in Java.

    Off the top of my head, I suspect you will find that internal HashMaps ultimately work best for your purposes.

    I wrote a little game (Tyrant - GPL source available) using a similar sort of dynamic object model featuring HashMaps, it worked great and performance was not an issue. I used a few tricks in the get and set methods to allow dynamic property modifiers, I'm sure you could do the same kind of thing to implement your signals and parent/child relations etc.

    [EDIT] See the source of BaseObject how it is implemented.

提交回复
热议问题