Reputation: 133
The idea is to get the current year that the system is running in, then name the study record after the year and therefore refer to it as the current year.
Basically just get the string variable and then use it as the name of an object. I have seen similar but not accurate as I want it and lack the explanation I am looking for.
Date now = new Date();c // get the current date
String CurrentYearRecord = Integer.toString(now.getYear()); // set a string variable that I will use to name my object
StudyRecord CurrentYearRecord = new StudyRecord(); // name my object the string year that I got from the previous line.
Upvotes: 0
Views: 101
Reputation: 339
You can use a HashMap
to store the name you want as key and use the value in the value of HashMap
. But that's not exactly naming a variable in runtime.
Upvotes: 0
Reputation: 1918
Unfortunately, manipulating variable names at runtime is not possible in Java language. This kind of feature is only possible in dynamic languages, like Python or Javascript.
In plain java, you can use a Map to achieve what you need:
Map<String, StudyRecord> records;
// init your map and fill it when relevant
StudyRecord currentYearRecord = records.get(Integer.toString(now.getYear()))
If you really need this feature, have a look at Groovy, which is a dynamic language running on the JVM with a close syntax to Java.
Upvotes: 2