开发者

How to extend my jar later with another .jar or .java

I imagine my application like this: I have an application for encrypting files. And I want to extend ciphers in my application(jar) with another cipher later. So, I will have a folder with ciphers (jar or java files) and my application will read the files from this folder. Then, in GUI, there will be a list with files(jar or java), which have a method encrypt and decrypt (I would test it with reflection). And user will choose 开发者_StackOverflow社区one.

Could someone give me an advice? How make it, that it could be extended? Or how my application(.jar) could work with another .jar, .java file(read them and run them)?


Another way to do this would be the java.util.ServiceLoader mechanism. (Read the documentation.)

Your additional jar would contain a file META-INF/services/my.package.Cipher listing all implementations of your Cipher interface (or abstract class), and then you can say

ClassLoader cipherLoader =
    new URLClassLoader(new URL[]{new URL("jar:file:myAdditional.jar")},
                       Cipher.class.getClassLoader());
ServiceLoader<Cipher> serviceLoader = ServiceLoader.load(Cipher.class, cipherLoader);
for(Cipher c : serviceLoader) {
    c.encrypt(...);
}

Using ServiceLoader mandates that your implementations have public no-argument constructors - if they don't have, use instead a ServiceLoader for some factory interface.

The URL should be either a jar: URL to the jar file in which the classes are, or a non-jar URL which points to the root directory where the .class files are in (in their package structure).


I would check out the Java Extension Mechanism.

This document describes the mechanism provided by the Java™ platform for handling optional packages. An optional package is a group of packages housed in one or more JAR files that implement an API that extends the Java platform. Optional package classes extend the platform in the sense that the virtual machine can find and load them without their being on the class path, much as if they were classes in the platform's core API.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜