我需要允许用户通过配置文件在运行时指定接口(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/