简体   繁体   English

PsiClass 到 java.lang.Class

[英]PsiClass to java.lang.Class

I'm developing plugin for IntelliJ IDEA.我正在为 IntelliJ IDEA 开发插件。 How can plugin get the name and version of libraries that are imported to the project that is being checked by plugin?插件如何获取导入到插件正在检查的项目中的库的名称和版本? I have PsiClass of the project, but cannot convert it to java.lang.Class.我有项目的 PsiClass,但无法将其转换为 java.lang.Class。 Maybe there's the way to get ClassLoader from PsiElement?也许有办法从 PsiElement 获取 ClassLoader?

super.visitImportStatement(psiImport);
Class importedClass = Class.forName(psiImport.getQualifiedName(), true, psiImport.getClass().getClassLoader());

PsiImport.getClass().GetClassLoader() - returns ClassLoader of class PsiImportStatementImpl instead of ClassLoader of class that I've imported. PsiImport.getClass().GetClassLoader() - 返回 class PsiImportStatementImpl 的 ClassLoader 而不是我导入的 class 的 ClassLoader。

IntelliJ does mostly static analysis on your code. IntelliJ 主要对您的代码进行 static 分析。 In fact, the IDE and the projects you run/debug have completely different classpaths.事实上,IDE 和您运行/调试的项目具有完全不同的类路径。 When you open a project, your dependencies are not added to the IDE classpath.打开项目时,您的依赖项不会添加到 IDE 类路径中。 Instead, the IDE will index the JARs, meaning it will automatically discover all the declarations (classes, methods, interfaces etc) and save them for later in a cache.相反,IDE 将索引 JARs,这意味着它将自动发现所有声明(类、方法、接口等)并将它们保存在缓存中以供以后使用。

When you write code in your editor, the static analysis tool will leverage the contents of this index to validate your code and show errors when you're trying to use unknown definitions for example.当您在编辑器中编写代码时,static 分析工具将利用此索引的内容来验证您的代码并在您尝试使用未知定义时显示错误。

On the other hand, when you run a Main class from your project, it will spawn a new java process that has its own classpath.另一方面,当您从项目中运行主 class 时,它将生成一个新的java进程,该进程具有自己的类路径。 This classpath will likely contain every dependency declared in your module.这个类路径可能包含在你的模块中声明的每个依赖项。

Knowing this, you should now understand why you can't "transform" a PsiClass to a corresponding Class .知道了这一点,您现在应该明白为什么不能将PsiClass “转换”为相应的Class

Back to your original question:回到你原来的问题:

How can plugin get the name and version of libraries that are imported to the project that is being checked by plugin?插件如何获取导入到插件正在检查的项目中的库的名称和版本?

You don't need to access Class objects for this.您不需要为此访问Class对象。 Instead, you can use IntelliJ SDK libraries .相反,您可以使用IntelliJ SDK 库 Here's an example:这是一个例子:

Module mod = ModuleUtil.findModuleForFile(virtualFile,myProject);

ModuleRootManager.getInstance(mod).orderEntries().forEachLibrary(library -> {

  // do your thing here with `library`

  return true;
});

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

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