8

I have tried unsuccessfully for a few hours now to edit the java files in a jar I am using as a library. I have marked the resource as a content root and as a source root but I am still unable to edit the code in the jars. The project compiles and runs correctly but I need to make an adjustment to a resource file and cannot; I have tried every project structure I could think of. Is it just impossible? All help is appreciated.

tony stew
  • 105
  • 1
  • 1
  • 8
  • Extend the resource file in your project and implement whatever you want to implement. – ifly6 Nov 19 '16 at 23:23
  • I tried to copy the text of the java file and then create a new writable file in the same resource directory but it gives me this: "Cannot modify the read only directory". – tony stew Nov 19 '16 at 23:30

1 Answers1

7

It is not recommended to edit JAR files. From the perspective of reproducibility1, it is better to:

  1. Get hold of the source tree for the library
  2. Check it into your version control (or fork it on Github)
  3. Modify and build it
  4. Use the resulting JAR instead of the original JAR

Another approach is to "overlay" the changes you want to make by creating a another JAR with the alternative version of the resources and placing it earlier in the application classpath.

But if neither of those works for you, you can use the jar command from the command line to modify a JAR file:

  1. Use jar -x ... to extract the files to a temporary directory tree
  2. Apply what ever changes need to be made to the tree
  3. Use jar -c .... to create a new JAR from the tree.

Read the manual entry for the jar command for more details. Signing the new JAR with the original keys would be an issue if you are not the original signer, but I doubt that that is relevant to you.


1 - The point is that the next guy maintaining your code needs to know what you did to the library JAR that you "edited", in case he needs to do the same procedure with another version of the JAR. If you do it by hand, he has no choice but to do a forensic comparison of the differences between the original and your edited version. And that assumes that the original JAR can still be obtained. Note that "the next guy" could be you ... in a couple of months or years time, when you have forgotten exactly what you did.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • But when using jar -x ... I get Decompiled .class file that is read-only in IntelliJ... How can I edit these files then? – Daniel Jun 01 '21 at 08:16
  • I repeat: *It is not recommended to edit JAR files.* But if you insist ... copy and paste the decompiled Java code to new files. Beware that **there are no guarantees** that the decompiled Java code is valid Java, or that it is functionally equivalent to the .class files you decompiled. – Stephen C Jun 01 '21 at 09:50