简体   繁体   中英

Scala type comparison not working

def getParentOfType[T <: PsiElement](element: PsiElement, aClass: Class[T], strict: Boolean = false): Option[T] = {
  System.out.println(aClass.isInstance(element), aClass, element.getClass)
  ...

getParentOfType(el, classOf[JSClassImpl])

Prints the following:

(false,class com.intellij.lang.javascript.psi.ecmal4.impl.JSClassImpl,class com.intellij.lang.javascript.psi.ecmal4.impl.JSClassImpl)

Shouldn't these evaluate to true?

At the moment the workaround is:

System.out.println(aClass.toString == element.getClass.toString)

This seems ridiculous. I've tried everything!

And then when I return a Option(el.asInstanceOf[T]) from the method, I get the following error whenever I try to use it:

java.lang.ClassCastException: com.intellij.lang.javascript.psi.ecmal4.impl.JSClassImpl cannot be cast to com.intellij.lang.javascript.psi.ecmal4.impl.JSClassImpl

I have a feeling it has something to do with class loaders.

ClassCastException when casting to the same class

From IntelliJ support forums:

you should note that plugins have their own ClassLoader.

http://devnet.jetbrains.com/message/5259550;jsessionid=13C3F98277311F5EFFFAFD3135B42CEA

See the issue recorded here

At the moment isInstanceOf/asInstanceOf don't support (upper bounded) type parameters so it parametric polymorphism is not possible even if the type parameter has a manifest.

Oh success. Glorious success!

This typing business was a diversion.

So the problem turned out to be with IntelliJ's use of separate class loaders for each plugin.

Basically I was receiving objects from a different class loader, which meant all comparisons would fail.

In retrospect, this was broken in the Java code, so it could never have been Scala's fault.

Thanks to everyone who answered, sorry to waste your time, but I did learn a lot about TypeTags, Manifests, etc. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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