简体   繁体   中英

Loading external classes

I am trying to load a class from a directory which I specify. I have done some research and made this:

ArrayList<Object> plugins = new ArrayList<Object>();
ClassLoader loader = Reflection.class.getClassLoader();

public Reflection()
{
    load();
}

public void load()
{

    File f = new File(Full directary);

    ClassLoader loader = null;
    try
    {
        loader = new URLClassLoader(new URL[]
        { f.toURI().toURL() }, getClass().getClassLoader());
    }
    catch (MalformedURLException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    for (File classFile : f.listFiles(new FilenameFilter()
    {
        public boolean accept(File dir, String name)
        {
            return name.endsWith(".class");
        }
    }))
    // Start for loop.
    {
        try
        {
            String filename = classFile.getName();
            System.out.println(filename);
            Class<?> cls = loader.loadClass(filename.replace(".class", ""));
            System.out.println(cls.getSuperclass().getName());
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

I am getting a NoClassDefFoundError error:

Exception in thread "main" java.lang.NoClassDefFoundError: mTest123g (wrong name: net/xcaliber/reflection/Test)

It finds the class fine, but then can't load it. I have made a basic interface:

String getName();

That's all that's in it; here is the class I am loading:

public Test()
{
    // TODO Auto-generated constructor stub
}

@Override
public String getName()
{
    return "Test";
}

This does implement the interface.Let me know the problem with it .

Obviously you have a mess up with class and file names.

Exception in thread "main" java.lang.NoClassDefFoundError: mTest123g (wrong name: net/xcaliber/reflection/Test)

So, you loading it as java mTest123g. Class loader expects a mTest123g.class not a Test class inside some net.xcaliber.reflection package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM