0

I have a use case where I have to generate functions based on a template, preferably in runtime. For e.g. let's say I have a function

public void function1(){
    //do something
}

Now, let's say I want to generate 50 more functions that does exactly the same thing, how can I achieve that? I understand I can hardcode 50 functions like this:

public void function3(){
    //do the same thing
}
public void function4(){
    //do the same thing
}
.
.
public void function50(){
    //do the same thing
}

But, I want to know if this can be generated during compile/runtime to keep the code clean.

PS: Calling the same function in a for loop or using classes is not possible for my use case as I need to have 50 different functions as a part of the code.

shmosel
  • 49,289
  • 6
  • 73
  • 138
Shashaank Sivakumar
  • 417
  • 2
  • 5
  • 13
  • 2
    Why???????????? – shmosel Aug 07 '19 at 01:38
  • You want to generate 50 functions that do the same thing but you want to "keep the code clean"..... – Claire Aug 07 '19 at 01:43
  • The reason why I want to achieve this is because of a limitation of a tool that my application depends on. It is a load testing tool that handles distribution of traffic between these functions. Hence, it is mandatory that they are declared as functions in my code. – Shashaank Sivakumar Aug 07 '19 at 01:47
  • How would you know whether you have 50 functions or one? Note that "name of function" and "code of function" are different things. If you just want 50 references, then look into ```java.util.functional```. Come to think of it, even if you manually wrote 50 different copies of the same function body, I see no immediate reason why the compiler cannot combine them. –  Aug 07 '19 at 01:59
  • potentially you can generate a class containing a function to a file at run time and then you can load the class dynamically. – Serge Aug 07 '19 at 02:40
  • @Serge how can I do that? – Shashaank Sivakumar Aug 07 '19 at 17:03
  • check this: https://stackoverflow.com/a/6219855/1143850; you will need to generate and compile the class from your java process. Than you should be able to load the '.class' file. – Serge Aug 07 '19 at 18:48

0 Answers0