【问题标题】:Java: with code add a external library from a FolderJava:使用代码从文件夹中添加外部库
【发布时间】:2020-01-18 12:35:28
【问题描述】:

如标题所述,

我的结构基本上是这样的: Structure of the Project

基本上有两个文件夹:com 和 JsonJ 与 jar 文件。

如何获取作为库的 jar 文件并在代码的帮助下将其作为库添加到项目中?

【问题讨论】:

    标签: java package shared-libraries add external


    【解决方案1】:

    如果您的问题是加载 JAR,然后从中加载一个类,您将必须创建一个新的 URLClassLoader 实例,然后使用它来加载您的类。这是一个示例方法。

    public class AddToClasspathAndLoad{
        public static void main( String[] args ) throws MalformedURLException{
            URL[] urls = new URL[] { new URL( "file:///<absolute-path-to-jar-or-folder>" ) };
            URLClassLoader cl = ( (URLClassLoader) AddToClasspathAndLoad.class.getClassLoader() ).newInstance( urls );
    
            tryIt( cl );
        }
    
        private static void tryIt(URLClassLoader cl) {
            try {
                Class<?> c = cl.loadClass( "<fully-qualified-class-name>" );
                System.out.println( c.getName() );
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2017-07-11
      • 2011-11-21
      • 1970-01-01
      • 2016-05-10
      • 2022-11-21
      相关资源
      最近更新 更多