I have a jar file, which I dynamically load during execut开发者_Python百科ion of my java file (say my.java). I do it this way:
File newFile = new File("path");
JarFile newJar= new JarFile(newFile);
Now there is a particular java file inside this jar, which I know the name of (say known.class). I want create an object of this known.class, and call a method inside it from my.java.
I am not sure how to go about this. Can any one help? I tried looking online, but didn't find anything helpful.
Thanks.
You need a .class
file (compiled java code) inside the jar, not a .java
file. If you have this, add the .jar to your classpath, or to one of the directories in your classpath, and then you can simply reference the Object from your Java code.
Ie:
MyObject newObj = new MyObject();
Here's how your specify the jar in the classpath:
java -classpath ".;myjar.jar" org.mine.MyClass
Edit: Since you don't want to change the classpath, try something like this:
File file = new File("/path/to/myjar.jar");
URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("org.mine.myclass")
You need to create a URLClassLoader
not a JarFile
. Reading the doc for ClassLoader will get you going, and also for Class
.
精彩评论