开发者

Java program using a class from a JAR file

开发者 https://www.devze.com 2023-02-03 05:46 出处:网络
I\'ll try to phrase this as best I can. I have a program which has an API-like functionality - it uses reflection to dynamically call methods from within a class. In this instance:

I'll try to phrase this as best I can. I have a program which has an API-like functionality - it uses reflection to dynamically call methods from within a class. In this instance:

Server.java

public static void main(String[] args) {
    Class<?> clazz = Class.forName("DiHandler");
    StHandler out = (StHandler) clazz.newInstance();
    out.read();
}

DiHandler.java

// implements StHandler
import edu.ds.*;

public void read() {
    Ds aType = new Ds();
    aType = "134";
}

So DiHandler has a method read() which can contain anything, it doesn't matter to Server.java after compile time.

My problem is: DiHandler.java uses the class Ds from a JAR file. When I'm working on DiHandler.java in Eclipse (in a separate project from the project Server.java is in) I can add this JAR without a problem. But when I move DiHandler.class, after it's compiled, to be used by Server.class, how can it still use the JAR file?

I hope this makes some sense, I suppose another way to phrase it would be how can I allow DiHandler to call on a class from the JAR without editing the classpath?

Thanks very much in a开发者_StackOverflowdvance and sorry for any confusion or poor phrasing, I can only offer thanks and the customary offer of a pint for any assistance.

M


One way or another, you need to let the ClassLoader that loads DiHandler know how to load your Ds class. The easiest way is through the classpath.

The other way is to provide your own ClassLoader which you use to load DiHandler, with that ClassLoader knowing how to load Ds. This could be a subclass of URLClassLoader that allows you add URLs to JAR files on the fly. What it will look like in practice I can't say since I don't know the details of your context.


You can only use a class if the JVM has access to it. This means that class has to be in JVM's classpath.

There are a number of ways to place a jar in the classpath of a program. Perhaps, if you describe the environment your working in and the limitations your facing, someone will be able to help you find the right mechanism for placing the dependent jar on the classpath.

0

精彩评论

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