3

I'm working on a small, Android based application which is responsible for loading external code as a form of a plug-in. Application works as a runtime environment for the dex compiled classes (tasks) located on the sdcard while providing overview for those tasks/tests.

Let's say that I have a Service class, and a Test class (stored on sdcard). When my application starts, the Service and Test classes are loaded into my application. Through a common interface the Test class have an access to all available Services.

One of those Tests requires several Services. When I start my application and run this Test i get the following error:

System.err﹕ java.lang.ClassCastException: com.test.testcomponent.MathService cannot be cast to com.test.testcomponent.MathService
System.err﹕ at com.test.testcomponent.ServiceTest.onStart(ServiceTest.java:15)
System.err﹕ at com.test.doc.domain.routine.TestExecutor.execute(TestExecutor.java:27)
System.err﹕ at com.test.doc.domain.suite.AsyncTestRunner$6.run(AsyncTestRunner.java:122)
System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)`

The first thing which came to my mind was that in my application another ClassLoader is used. I have checked that but the application uses only one ClassLoader.

It also doesn't seem to be related to the device/phone on which the application is ran.

For loading external dex classes i use: org.smali:dexlib2:2.0.3

Resolved:

In the end I have used more than one ClassLoader which was causing the mentioned problem.

Community
  • 1
  • 1
Cativail
  • 1,040
  • 1
  • 9
  • 18
  • Related: http://stackoverflow.com/questions/5578797/java-exception-when-casting-to-itself – Andy Turner Jun 26 '15 at 16:20
  • 1
    You can *always* cast an object to its own class, so it follows from the exception that there are two different classes named `com.test.testcomponent.MathService`. This can only happen if they were loaded by different classloaders, or perhaps if they were both loaded by one buggy classloader. – John Bollinger Jun 26 '15 at 16:24
  • I'm using same loader for both **Test**s and **Service**s, To load the classes I'm using Android - **DexClassLoader**. What if i have two classes with the same name loaded - i will need to check that. – Cativail Jun 26 '15 at 16:33
  • Having one class in several "flavors" is a bad idea. If you want full access for testing extend the class-to-be-tested and/or use reflection to get access to private elements. – Robert Jun 26 '15 at 17:39
  • Bad idea or not - it still doesn't explain why it doesn’t work. – Cativail Jun 26 '15 at 17:58

0 Answers0