0

Is there a way to change the code of the java at runtime?I need to read java file from jar, change the code, recompile it and put into the jar. All of this should be done at runtime. The part I dont knwo is how to read the java file as a java file from jar file and change the code

user1574866
  • 275
  • 2
  • 6
  • 12
  • 2
    most of the chances it won't work since you have to reload the jar after the changes http://stackoverflow.com/a/60775/1057429 – Nir Alfasi Aug 07 '12 at 19:47
  • Could you be a little more specific / provide examples? – Jay Aug 07 '12 at 19:48
  • 9
    I think you should explain your ultimate goal, not the mechanism. There's probably a much better way (than recompiling a class) to do what you want. – Jim Garrison Aug 07 '12 at 19:48
  • Don't mean to be a drag but the part you don't know is the easy part. The part that is going to be rough is replacing the old bytecode with the new one at runtime. May be something like JRebel might get you by depending on your requirements. – mprivat Aug 07 '12 at 19:48
  • 3
    There is no java file anymore. The jar only contains a class file. There are a number of ways to change the code a JVM runs at runtime. It might help to have more detail about what kind of things you are trying to change. For example, you might just want a plugin architecture. The code is changed at compile time for the plugin but after compile time for the main application. You might need to modify bytecode at runtime, as BCEL and ASM let you do. Or you might use the Java 6 Compiler class. – John Watts Aug 07 '12 at 19:49
  • You should use interfaces to communicate with these jars and use the [Decorator design pattern](http://en.wikipedia.org/wiki/Decorator_pattern) to change behavior dynamically at runtime. – Luiggi Mendoza Aug 07 '12 at 19:50
  • Possibly the Java Scripting API might be of interest. BeanShell for instance is a javaish language. – Joop Eggen Aug 07 '12 at 21:18
  • I just cannot see another solution for my problem. I am extending the software where I need to add my new classes. Adding my classes to the jar file is simple, but it is not enough, I need also declare them in the array. I could simply write subclass of this class with array and force the superclass to override the array, but the problem is that the array is declared as static final. But without updating that array the application will not see my classes. – user1574866 Aug 07 '12 at 22:20
  • Are you sure the license of the software you are extending permits such a modification? What is this software? Is it an open source project we can look at? – John Watts Aug 09 '12 at 13:07
  • Possible duplicate by the same user: http://stackoverflow.com/questions/11801155/how-to-add-new-java-classes-to-the-existing-classes-in-jar-file – Simon Forsberg Oct 19 '12 at 12:09

0 Answers0