Sunday, November 5, 2017

java.lang.ClassCastException for the same class com.sample.test.Test cannot be cast to com.sample.test.Test - Adobe Experience Manager(AEM)

java.lang.ClassCastException for the same class com.sample.test.Test cannot be cast to com.sample.test.Test - Adobe Experience Manager(AEM)

We were facing a strange ClassCastException - ClassCastException pointing to the same class in Adobe Experience Manager(AEM)

java.lang.ClassCastException: com.sample.test.Test cannot be cast to com.sample.test.Test

While analyzing through depfinder - http://localhost:4502/system/console/depfinder, there is two version of the same class available from two different packages.

But this class is only defined in one of the package and referred in the other package, after analyzing the Sling class loading is little different - If one of the class com.sample.test.Test is referred from different package, Sling copies the classes locally to the target package and if the target package export the same package(<Export-Package>) -  com.sample.* then Sling export the classes copied from other package that matches the export pattern, in this case our target package is already exporting com.sample.* so two version of same class is available now. This will lead to the ClassCastException specified above.

To fix this issue, we can change the target package pom.xml file to restrict the export of referred classes from other package.

<Export-Package>com.sample.*,!com.sample.test</Export-Package>

Please make sure the restricted package - !com.sample.test is kept after the wider package - com.sample.*

Now only one version of the class from source package is available for reference.


No comments:

Post a Comment