Java - 动态加载类

时间:2012-10-19 16:08:56

标签: java class plugins dynamic classloader

我正在创建一个插件系统(我的第一次尝试),查看其他人的代码我正在尝试拼凑我自己的类加载器并从目录中加载插件(这些将是类文件)

我的问题是,每当我尝试使用类加载器加载类时,类加载器都找不到引用该程序的插件中的任何导入。 (即:MyClass扩展插件,com.mgmc.plugins noclassdeffound)不同的命名空间?

一些示例代码: 类加载器:

/*


* To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mcgm.game.provider;

import com.mcgm.utils.Misc;
import com.mcgm.utils.Paths;
import java.awt.AWTPermission;
import java.io.*;
import java.net.MalformedURLException;
import java.net.SocketPermission;
import java.net.URL;
import java.security.CodeSigner;
import java.security.CodeSource;
import java.security.Permissions;
import java.security.ProtectionDomain;
import java.util.PropertyPermission;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Tom
 */
public class GameClassLoader extends ClassLoader {
private final ProtectionDomain domain;
private final URL base;

public GameClassLoader(final URL url) {
    base = url;
    final CodeSource codeSource = new CodeSource(base, (CodeSigner[]) null);
    domain = new ProtectionDomain(codeSource, getPermissions());
}

public void loadGames() {
    for (File f : Paths.compiledFolder.listFiles()) {
        try {
            Class c = loadClass(f.getPath());
            Misc.outPrint(c.getName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(GameClassLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

private Permissions getPermissions() {
    final Permissions ps = new Permissions();
    ps.add(new AWTPermission("accessEventQueue"));
    ps.add(new PropertyPermission("user.home", "read"));
    ps.add(new PropertyPermission("java.vendor", "read"));
    ps.add(new PropertyPermission("java.version", "read"));
    ps.add(new PropertyPermission("os.name", "read"));
    ps.add(new PropertyPermission("os.arch", "read"));
    ps.add(new PropertyPermission("os.version", "read"));
    ps.add(new SocketPermission("*", "resolve"));
    ps.add(new FilePermission(Paths.compiledFolder.getPath(), "read,write,delete"));
    ps.setReadOnly();
    return ps;
}

@Override
@SuppressWarnings("rawtypes")
public Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
    Class clazz = findLoadedClass(name);

    if (clazz == null) {
        try {
            byte[] bytes = loadClassData(name);
            clazz = defineClass(name, bytes, 0, bytes.length, domain);
            if (resolve) {
                resolveClass(clazz);
            }
        } catch (final Exception e) {
            clazz = super.loadClass(name, resolve);
        }
    }

    return clazz;
}

public byte[] loadClassData(final String name) {
    try {
        final InputStream in = getResourceAsStream(name.replace('.', '/') + ".class");
        final byte[] buffer = new byte[4096];
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        int n;
        while ((n = in.read(buffer, 0, 4096)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    } catch (IOException ex) {
        Logger.getLogger(GameClassLoader.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;

}

@Override
public URL getResource(final String name) {
    try {
        return new URL(base, name);
    } catch (final MalformedURLException e) {
        return null;
    }
}

@Override
public InputStream getResourceAsStream(final String name) {
    try {
        return new URL(base, name).openStream();
    } catch (final IOException e) {
        return null;
    }
}
}

我正在加载的插件:(也没有找到注释)

import com.mcgm.GameInfo;
import com.mcgm.game.Minigame;
  @GameInfo(name = "RandomGame",
description = "A really long and boring game.",
authors = {"Tom", "Is", "The", "Greatest"},
version = 0.1,
maxPlayers = 100,
teamBased = false,
teamAmount = -1,
PvP = false)
public class game extends Minigame {
}

我如何调用要加载的类:

  GameClassLoader classLoader = new GameClassLoader(Paths.compiledFolder.toURI().toURL());
            classLoader.loadClass("game", true);

我认为对于那些知道自己在做什么的人来说,这是微不足道的!

2 个答案:

答案 0 :(得分:4)

最后!经过一天半的搜索,瓦肯人向我指出了正确的方向: 我将GameClassLoader改为:

public GameClassLoader(final URL url, ClassLoader parent) {
    super(parent);

最后将基本网址添加到getResourceAsStream()

final InputStream in = getResourceAsStream(base.getFile() + "/" + name.replace('.', '/') + ".class");

非常感谢你的帮助!

答案 1 :(得分:0)

尝试将前导斜杠添加到资源路径中: final InputStream in = getResourceAsStream("/" + name.replace('.', '/') + ".class");

这是我每次打电话getResourceAsStream()时都要尝试的事情。我刚刚再次尝试过这个。这里的路径是相对于用于调用getResourceAsStream()的类的包,因此需要使用前导斜杠来表示&#34;从root开始。&#34;