PsiClass to java.lang.Class - java

I'm developing plugin for 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. Maybe there's the way to get ClassLoader from PsiElement?
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.

IntelliJ does mostly static analysis on your code. In fact, the IDE and the projects you run/debug have completely different classpaths. When you open a project, your dependencies are not added to the IDE classpath. 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.
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.
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. 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.
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. Instead, you can use IntelliJ SDK libraries. Here's an example:
Module mod = ModuleUtil.findModuleForFile(virtualFile,myProject);
ModuleRootManager.getInstance(mod).orderEntries().forEachLibrary(library -> {
// do your thing here with `library`
return true;
});

Related

Cannot extend CDT CEditor: "The hierarchy of the type '' is inconsistent"

When trying to write a class that extends I get the error message:
The hierarchy of the type 'MYEditor' is inconsistent.
import org.eclipse.cdt.internal.ui.editor.CEditor;
public class MYEditor extends CEditor {
}
This answer says:
These errors happened because some interface/class in the hierarchy
cannot be resolved.
This indicates that eclipse cannot find a class in the hierarchy. But when I use the class in my plugin.xml, it works. I am using it like this:
<editor
class="org.eclipse.cdt.internal.ui.editor.CEditor"
contributorClass="org.eclipse.cdt.internal.ui.editor.CEditorActionContributor"
default="true"
filenames="*.grasp, *.c"
icon="icons/small.png"
id="de.blub.ide.myeditor"
name="My Editor">
</editor>
This works, but lacks a few features that I need for my plugin. That's why I want to use a class that inherits from CEditor.
This answer didn't work, to (remove and add JRE System Library).
I've also read that the jar file needs to be put in the Classpath section of the plugin.xml. But the "Add" and "New" Buttons don't provide a way to chose an external jar file. I can manually copy that jar file from "~/.p2/pool/plugins" into my projects lib folder, but that didn't help.
Plug-ins reference code in other plug-ins by including the other plug-in in their dependencies list. This is the Require-Bundle entry in the plug-in's MANIFEST.MF.
In the MANIFEST.MF/plugin.xml/build.properties editor you can set the dependencies in the 'Required Plug-ins' section on the 'Dependencies' page.
Do not copy plugin jars, do not put plugin jars in the Java Build Path.
But note that extending internal classes is against the Eclipse API Rules of Engagement. Internal classes may change without warning and may be different in older releases.
The CDT Plug-in Programmer's Guide covers the official APIs for Eclipse CDT.

Android Annotation Processor accessing Annotated classes from different modules

I'm having an Android Studio project with 2 modules: A and B. (I do not include here the Annotation Processor and the Annotations module)
B depends on A.
B is an Android Library Module, and A is simple Java library Module. I'm also having an Annotation Processor on module B.
The problem I'm facing is:
I want to generate some code, based on annotated files placed in both modules - A and B. The problem comes from the way the Annotation Processor works - only with source code files *.java - not with compiled *.class ones. Unfortunately, during the compilation of B, the Annotation Processor doesn't have access to those source files from A...
The only thing, I was able to think about as a kind of solution, even an ugly one, was to include the folder with the annotated classes from module A as a source set to module B. This way I give module B access to those files during compilation.
sourceSets {
main {
java {
srcDirs = ['src/main/java', '../module_A/src/main/java/path/to/annotated/classes/folder']
}
}
}
That solves the problem - now the Annotation Processor has access to all the annotated classes from both modules, but...
Unfortunately, it introduces another issue... those annotated classes from module A, are now compiled twice. And they are included in the module A's JAR file and in the module B's AAR file.
Question 1: Is there another way to access those source files of module A, from the Annotation Processor running on B??? (From what I was able to find, the answer is NO, but checking...)
Question 2: How can I exclude those compiled files (the repeated ones) from the AAR final package of module B?
Question 3: Maybe... that's an absolutely wrong approach? Any suggestions?
Thanks in advance!
Nop, you can not achieve what you want using just java.lang.model API. At least not without some additional tricks.
The issues is not with binary-vs-source. Annotation processors can use Elements#getTypeElement to interospect compiled classes as well as source-defined classes:
Elements elementUtil = processingEnvironment.getElementUtils();
TypeElement integerClass = elementUtil.getTypeElement("java.lang.Integer");
TypeElement myClass = elementUtil.getTypeElement("currently.compiled.Class");
But you still need to have class on compilation classpath to observe it, and the class must be in process of being compiled to be visible to getElementsAnnotatedWith.
You can work around later limitation by using a tool like FastClasspathScanner: it will use it's own mechanisms to find annotations in compiled bytecode, and report them to you separately from compilation process. But you can not work around the classpath issue: if you don't have some dependency in compilation classpath, it can not be processed. So you have to compile modules together — either by merging them into one (as you did) or via declaring one to depend on another. In later case you might not be able to use getElementsAnnotatedWith, but getTypeElement and FastClasspathScanner will work.

Same class different version, dependencies, NoSuchMethod

I am working on a web project that has 2 different dependencies being pulled into war file of the same class
(different versions, different package)
One is :
com.google.common.collect, and the other is Guava API package. When I run this service on websphere application server, it throws NoSuchMethodFound Exception at ImmutableList.copyOf. It clearly is loading the earlier class instead of the class from Guava which has the required functions.
I cannot change any dependency, how ever is it possible for me to override a particular dependency by other using maven?
How should I solve this problem?
If you have control over the WebSphere installation, you can also try this:
locate the jre lib directory of your application server (/WebSphere/AppServer/java/jre/lib)
create a directory 'endorsed' put your required jars into this directory( Guava API).
The jars in this directory will be loaded first and override what you have in you war file.
This is not recommended but you can use it as patch to override the conflicting classes.
The first matched class found on the classpath is used. Therefore if you can specify the classpath in different ways to try and influence what class is picked up. (i.e. specify the class that you want loaded first in the classpath). This is not a good practice because the Java specification does not guarntee to use the classpath order.
A better solution would be to manage the classloading yourself in the code. This can be done by
`ClassLoader myClassLoader = new MyClassLoader(libPath);
Object1 obj1 = myClassLoader .loadClass("com.google.common.collect", true);'
Now if a classloader attempts to load classes from a library, the dependent classes would be loaded by the same classloader that does not have access to the other libraries and dependencies.
Note: That if you use this and want to move to OSGi in the future you will incure some pain having to remove this code. Therefore try to limit it's use or switch to OSGi early!

How do I locate a clashing class in the IntelliJ classpath?

I'm trying IntelliJ IDEA after many years as an Eclipse user. At the same time, I'm working on a project that I've inherited with many dependencies.
One class will not compile, because IDEA claims that a method in another class does not exist. I can see the method in its source. Control-clicking on the class name in the IDEA editor takes me to the source that looks OK.
My hypothesis is that the compiler isn't using the class compiled from the source within the project, but a class with the same name, somewhere among my dozens of library jars.
How can I find out where IDEA's compiler is finding the clashing class?
CTRL-N and entering the class name should show you all of the matching classes from across the classpath, and which directory/JAR they're in. If there's a clash, you should have duplicates in that list.
Another possibility is that the source you have for the referenced class doesn't match the compiled version of that class.

Package contains object and package with same name

I am having problems compiling some Scala with Maven or Eclipse where I try to import a class from a Java jar which contains both a namespace and class of the same name.
I can compile with scalac, however.
E.g. the Java project (jar) contains:
src/foo/bar.java
src/foo/bar/some_resource.txt
-> foobar.jar
Scala project references foobar.jar
Foobartest.scala:
import foo.bar
class foobartest {
}
The compiler complains with:
package foo contains object and package with same name: bar
one of them needs to be removed from classpath
Using Maven 3.0.03/Eclipse 3.7.1 with Scala 2.9.0.1 (and maven-scala-plugin).
The jar which I am having problems with is jenkins-core-1.399.jar - it definitely contains several instances where there is a namespace and object of the same name.
I am attempting to write a Jenkins plugin in Scala (I could do this in Java but would prefer scala since all of our libraries are in scala), which is dependent on using Maven -
https://wiki.jenkins-ci.org/display/JENKINS/Plugin+tutorial.
That kind of limitation was outlined in SI-4695: package object misbehaves in the presence of classfiles.
As suggested in SI-2089 (naming restriction makes some jars unusable), you could try and use the "resolve-term-conflict", as implemented in changeset 25145:
Added a -Y option to resolve namespace collisions between package and object.
It's a blunt instrument: if people have lots of these conflicts they need to resolve in individually nuanced fashion, they'll probably remain out of luck.
val termConflict = ChoiceSetting ("-Yresolve-term-conflict", "strategy", "Resolve term conflicts", 113 List("package", "object", "error"), "error")
// Some jars (often, obfuscated ones) include a package and
// object with the same name. Rather than render them unusable,
// offer a setting to resolve the conflict one way or the other.
// This was motivated by the desire to use YourKit probes, which
// require `yjp.jar` at runtime. See SI-2089.
The actual compiler option is "-Yresolve-term-conflict:strategy" where strategy is either package, object, error.

Categories

Resources