0

I get path to .jar file as user input of my java application. I need to add one class that is on my class path to that .jar file and then send the .jar file to external service (over network). The service on the other site must be able t load classes from the .jar file including the one I added in my application.

The solution should have these properties:

  • universal: should work for any thinkable .jar containing classes user can give me.
  • automatic: class addition must by done by my java application.

The class to be added to .jar file has name that does not collide with any other class in that JAR.

Rasto
  • 17,204
  • 47
  • 154
  • 245

3 Answers3

1

Since jars are regular zip files, you can use the facilities provided by java.util.zip.

mbelow
  • 1,093
  • 6
  • 11
  • 3
    I would say java.util.jar instead. – Edwin Dalorzo Nov 27 '12 at 01:01
  • @EdwinDalorzo but how do I write something into existing .jar with using `java.util.jar` or `java.util.zip` package? Both packages seems to only allow reading as I see it... – Rasto Nov 27 '12 at 01:42
  • See this on how to add a file to an existing archive: http://stackoverflow.com/questions/3048669/how-can-i-add-entries-to-an-existing-zip-file-in-java – mbelow Nov 27 '12 at 11:58
0

To add upon what others have said, if you are needing to load the JAR on the other end, you should examine http://docs.oracle.com/javase/7/docs/api/java/net/URLClassLoader.html

caranmegil
  • 28
  • 3
0

I understand that you have a class on your classpath, and what you want to do is to get its bytearray representation for the purpose of injecting it into an existing JAR file.

Neat.

Hava a look at the javax.tools package, available with JDK 1.6 and up:

http://docs.oracle.com/javase/6/docs/api/javax/tools/package-summary.html

You can programmatically compile code and serialize bytecode using mechanisms available there. If not, ASM could be of help as well: http://asm.ow2.org/

Isaac
  • 16,458
  • 5
  • 57
  • 81
  • Hmm, I do not really need to compile anything... In my application project there will be a compiled class. We can treat it as a resource that I need to inject into existing JAR. – Rasto Nov 27 '12 at 01:12
  • 1
    If you can locate the actual `.class` file, then all you need to do from there on would be to use the `java.util.jar` package, as per other answers that were suggested here. – Isaac Nov 27 '12 at 01:20