Java classes with dynamic fields

后端 未结 5 806
孤独总比滥情好
孤独总比滥情好 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:18

    Type safe without casts if possible for custom code that works on the dynamic fields (that code would come from plugins which extend the model in unforeseen ways)

    AFAIK, this is not possible. You can only get type-safety without type casts if you use static typing. Static typing means method signatures (in classes or interfaces) that are known at compile time.

    The best you can do is have an interface with a bunch of methods like String getStringValue(String field), int getIntValue(String field) and so on. And of course you can only do that for a predetermined set of types. Any field whose type is not in that set will require a typecast.

提交回复
热议问题