简体   繁体   English

加载外部类

[英]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: 我收到了NoClassDefFoundError错误:

Exception in thread "main" java.lang.NoClassDefFoundError: mTest123g (wrong name: net/xcaliber/reflection/Test) 线程“主”中的异常java.lang.NoClassDefFoundError:mTest123g(错误名称: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. 因此,您将其加载为java mTest123g。 Class loader expects a mTest123g.class not a Test class inside some net.xcaliber.reflection package. 类加载器期望某个net.xcaliber.reflection包中的mTest123g.class不是Test类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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