【问题标题】:Java: load User-defined interface implementation (from config file)Java:加载用户定义的接口实现(来自配置文件)
【发布时间】:2015-11-02 15:16:50
【问题描述】:

我需要允许用户在运行时通过配置文件指定接口的实现,类似于这个问题:Specify which implementation of Java interface to use in command line argument

但是,我的情况不同,因为在编译时不知道实现,所以我将不得不使用反射来实例化类。我的问题是......我如何构建我的应用程序,以便我的类可以看到新实现的 .jar,以便它可以在我调用时加载该类:

Class.forName(fileObject.getClassName()).newInstance()

?

【问题讨论】:

  • 你不需要做任何特别的事情。只要用户把jar文件放到classpath下,加载class就可以了。

标签: java dynamic reflection interface instantiation


【解决方案1】:

评论正确;只要 .jar 文件在您的类路径中,您就可以加载该类。

我过去用过这样的东西:

public static MyInterface loadMyInterface( String userClass ) throws Exception
{
    // Load the defined class by the user if it implements our interface
    if ( MyInterface.class.isAssignableFrom( Class.forName( userClass ) ) )
    {
        return (MyInterface) Class.forName( userClass ).newInstance();
    }
    throw new Exception("Class "+userClass+" does not implement "+MyInterface.class.getName() );
}

String userClass 是配置文件中用户定义的类名。


编辑

想一想,甚至可以使用以下方式加载用户在运行时指定的类(例如,在上传新类之后):

public static void addToClassPath(String jarFile) throws IOException 
{
    URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class loaderClass = URLClassLoader.class;

    try {
        Method method = loaderClass.getDeclaredMethod("addURL", new Class[]{URL.class});
        method.setAccessible(true);
        method.invoke(classLoader, new Object[]{ new File(jarFile).toURL() });
    } catch (Throwable t) {
        t.printStackTrace();
        throw new IOException( t );
    }
}

我记得在 SO 上的某处使用反射找到了 addURL() 调用(当然)。

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 2023-03-26
    • 1970-01-01
    • 2014-05-03
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 2017-02-10
    • 2011-10-30
    相关资源
    最近更新 更多