Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating fields dynamically java

i was wondering if their is any way to dynamically create a static field for a class during run-time using reflection or a related API. If needed i can use the java native interface to accomplish this task if someone could tell me the appropriate steps. I don't want to use any data structures such as a hash-map, as i am doing this completely for fun. Please don't suggest using maps as i am not using this for any real program this is a completely theoretical situation. Thanks.

like image 448
Josh Sobel Avatar asked Aug 10 '26 10:08

Josh Sobel


1 Answers

You could do this during class load time using bytecode manipulation.

This is a very complex solution though, so I'd consider other options.

It also does not help too much to have a new field that is not known at compile-time, because you cannot compile anything against it. If you are going to use reflection to access it, you might as well use a Map in the first place.

like image 171
Thilo Avatar answered Aug 12 '26 00:08

Thilo