I want to create java classes dynamically based on some results. Could please tell me if I can create it and add code inside. Thanks a lot for your help
-
2add some example of what you want to achieve and what you've tried so far – Halayem Anis Jun 26 '18 at 10:06
-
1Possible duplicate of https://stackoverflow.com/questions/2320404/creating-classes-dynamically-with-java – Sudhir Ojha Jun 26 '18 at 10:08
-
3You can. It will not help in your situation. That possibility exists for advanced stuff, that do not correspond to what you're trying to do. Try to prove me wrong by describing what you're trying to do, and a smarter way to do it will be pointed out to you. – kumesana Jun 26 '18 at 10:08
-
Well, at stretch, you could create a java file, compile and load similar to [this example](https://stackoverflow.com/questions/21544446/how-do-you-dynamically-compile-and-load-external-java-classes/21544850#21544850) – MadProgrammer Jun 26 '18 at 10:12
1 Answers
As said in the comments : "You can. It will not help in your situation."
Meaning : if you have to ask, you're probably not experienced/skilled enough to do that kind of stuff. Meaning : if you disregard this advice, you'll probably spend an inordinate amount of time trying to make something "work" that still has "subtle" flaws in it nonetheless. One example that comes to mind : you might be so unwary that you're overlooking the fact that the JVM and its classloaders operate by caching loaded classes, and this might defeat your intent of doing your class generation inside a loop. Or inside a web servlet, doing your class generation once for each request that comes in.
That said : you can invoke the compiler on a java source generated at runtime, and if you handle compile errors properly (is your "some input" completely sane ?) and if you see to it that the generated .class file ends up existing in the JVM's classpath (in a servlet container, that's probably going to break easy deployability) and if you consider all possible issues with classloading (I don't know myself what "all" issues are) then results might be as you hope for.
You've been warned. Take the warnings seriously.

- 18,113
- 4
- 33
- 52