Java:加载用户定义的接口(interface)实现(来自配置文件)

标签 java dynamic reflection interface instantiation

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

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

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

?

最佳答案

评论正确;只要 .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() 调用(当然)。

关于Java:加载用户定义的接口(interface)实现(来自配置文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31924118/

相关文章:

java - StringBuilder的deleteCharAt()函数 "String index out of range : 6 "

java - 处理器因任何原因停机时的 NiFi 数据安全

mysql动态sql

reflection - 使用可嵌入结构的通用函数

C# 泛型 如何获取作为参数传递给没有对象类型作为参数的泛型方法的类型?

c# - 为什么 GetProperty 找不到它?

将 "9632580147"转换为 int 时 Java 解析错误

java - 检查物体坐标是否满足要求

hibernate - 在运行时创建 Pojo,并在将 pojo 保存到磁盘后抛出类修剪错误?

c - 在c中动态获取属性