简体   繁体   English

Class.forName()无法找到其他项目文件的类路径

[英]Class.forName() is not able find classpath of other project file

I have created a plugin to fetch the fields of a particular .java file for that I am using following code: 我已经创建了一个插件来为我使用以下代码获取特定.java文件的字段:

Class<?> forName = Class.forName(refPath);//refPath = "xyz.test"
Field[] declaredFields = forName.getDeclaredFields();
for (Field field : declaredFields) {
    String name = field.getName();
}

When I deployed this plugin in to the workspace, it is perfectly working for its plugin project but not fetching fields for other project of same workspace. 当我将此插件部署到工作区中时,它可以完美地用于其插件项目,但不能为相同工作区的其他项目获取字段。 throwing exception ClassNotFound, obviously classloader is not able to find other projects file. 抛出ClassNotFound异常,显然是classloader无法找到其他项目文件。

Is there any way i can get the file information for other projects(plugin/non plugin)of same workspace where plugin is deployed? 有什么办法可以获取部署了插件的同一工作区的其他项目(插件/非插件)的文件信息?

AS stated in the comment, you need the java class containers (JAR?) to be in your classpath. 如评论中所述,您需要将Java类容器(JAR?)放入类路径中。

Whether you can do it statically, and add the other archive to your classpath when starting your JVM, Or you can try to add it dynamicaly. 是否可以静态地执行它,以及在启动JVM时将另一个归档文件添加到类路径,还是可以尝试动态地添加它。

To do it, here is what you can do : 为此,您可以执行以下操作:

/**
 * Adds a jar file dynamically to the current class path
 * @param jarFile
 */
private static void addToClassPath(File jarFile) {
    try {
        System.out.println("adding " + jarFile.getAbsolutePath() + " to classpath");
        URL u = jarFile.toURI().toURL();
        URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();

        /* Here is a trick to call URLClassLoader.addURL whereas this method is 'protected' */
        Class sysclass = URLClassLoader.class;
        Method method = sysclass.getDeclaredMethod("addURL", sysClassLoaderParams);
        method.setAccessible(true);
        method.invoke(sysloader, new Object[] { u });
    } catch (Exception e) {
        System.out.println("Error while updating classpath: "+ e.toString());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM