Is there away to generate Variables' names dynamically in Java?

后端 未结 10 2334
醉酒成梦
醉酒成梦 2020-11-28 14:46

Let\'s say that I need to generate variables to hold some input from the user (I don\'t know how many they are). Without using Array, ArrayList (an

10条回答
  •  一向
    一向 (楼主)
    2020-11-28 15:12

    You mean you want to generate variables named

    var0, var1, var2 and use them in your code.

    What is the difference when you use var[0], var[1], var[2], .....

    BUT

    You can generate a Java class dynamically at runtime which implements an Interface you are using in your normal code. Then you compile this class using a compiler (For example Janino) and then load the class at runtime. Than you have created a class dynamically.

    But i wonder, whether this is necessary for your usecase.

    EDIT

    I dont now for which usecase you are using this parameters but dynamic arguments you can use in Java like this example from here

    // calculate average
            public static double average( double... numbers )
            {
               double total = 0.0; // initialize total
    
              // calculate total using the enhanced for statement
              for ( double d : numbers )              
                 total += d;                          
    
              return total / numbers.length;
           } // end method average
    

提交回复
热议问题