java - eclipse plugin开发loadClass后getAnnotation()返回null?
伊谢尔伦
伊谢尔伦 2017-04-18 10:56:33
0
0
419

通过URLClassLoader加载project中的一个类,类中自定义的注解,然后getAnnotation总是返回空,求解……
已知eclipse插件中加载类的方法,并使用,如下

// 获取类加载器 project是选中文件的项目IJavaProject
String[] classPathEntries = JavaRuntime.computeDefaultRuntimeClassPath(project);
List<URL> urlList = new ArrayList<URL>();
for (int i = 0; i < classPathEntries.length; i++) {
    String entry = classPathEntries[i];
    IPath path = new Path(entry);
    URL url = path.toFile().toURI().toURL();
    urlList.add(url);
}

ClassLoader parentClassLoader = project.getClass().getClassLoader();

URL[] urls = (URL[]) urlList.toArray(new URL[urlList.size()]);
URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader);

然后通过这个语句获取Class

return Class.forName(name, true, classLoader);
// 或者这样 都又这个问题. 我先用的下面的方法,不可以又试了上面的方法也不行
return classLoader.loadClass(name);

获取Class后获取注解:topClass.getAnnotation(HeadApiProtocol.class)
永远都是null

要获取的类如下:

@HeadProtocol( needInit=true,timers="60")
public class Test {
......
}

我单独运行虚拟机,通过如下的方式和直接Class.forName(name)就可以正确获取注解,而在Plug-in中调用就获取不到注解。问题出在哪??求解啊!

urls = new URL[] {
    new File("D:/runtime-EclipseApplication/api_proj/bin/").toURI().toURL()
};
ClassLoader parentClassLoader = ClassLoader.getSystemClassLoader();
            
URLClassLoader classLoader = new URLClassLoader(urls, parentClassLoader);
Class<?> cls = Class.forName("com.test.TestAo", true, classLoader);
System.out.println(cls.getAnnotation(HeadProtocol.class));
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!