How to load Jar file in my program?

I'm trying to write a program that load classes and jar files .My app handle the plus operator .For this I have 2 class and one jar file :

1- Operator interface jar file in directory D:\operatorAPI (Operator interface is a jar file)

package OperatorAPI;

public interface Operator
{
    int calculate(int num1 , int num2);
}

2-class Plus in directory (D:\operators)

package operators;

import OperatorAPI.*;

public class Plus implements Operator
{
    public int calculate(int num1 , int num2)
    {
        return num1 + num2;
    }
}

3- Main class in directory D:\source\main :

package source.main;

import java.util.*;
import java.io.*;
import java.net.URL;
import java.net.URLClassLoader;
import operatorAPI.*;

public class Main
{
    public static void main(String[] args)
    {
        File file = new File("D:\\");
        URI uri = file.toURI();
        URL[] urls = new URL[] {uri.toURL}
        ClassLoader classloader = new URLClassLoader (urls);
        Class clazz = classloader.loadClass("operator.Plus");

        Operator instance = (Operator) clazz.newInstance();
        int output = instance.calculate(10,20);
        System.out.println("The result is :" + output);
    }
}

But when I run my Program in command line I get this exception : Exception in thread "main" java.lang.NoClassDefFoundError: operatorAPI/Operator

I think because Operator interface is a jar file I should load it to my program But I don't know How to do this . Can anyone help me?

Jon Skeet
people
quotationmark

Currently you're only using D:\ in your classpath:

File file = new File("D:\\");
URI uri = file.toURI();
URL[] urls = new URL[] {uri.toURL}
ClassLoader classloader = new URLClassLoader (urls);

If you want to use a jar file, you should specify that:

File file = new File("D:\\operator.jar");

If that's all you need your new classloader to load, that should be the only change you need. You might want to make this a command-line argument, mind you.

As you use Operator within your "driver" class, you'll need that in the classpath you run with though. For example:

java -cp operatorAPI.jar;. source.main.Main

You shouldn't need to add operator.jar to the classpath when compiling though... if the idea is to write a "pluggable" system, others should be able to add plugins without you knowing anything about them at compile time. Both your code and the plugins should just know about the shared interface.

people

See more on this question at Stackoverflow