1

Recently in my project I have encountered one issue I am casting an object of com.package1.class1 to com.package2.Class1 but its getting failed and giving me below error:

Caused by: java.lang.ClassCastException: com.package1.Class1 cannot be cast to com.package2.Class1

and code snapshot is as below:

if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
    ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
            savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
    for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) { //Exception received for this line

    }
}

Can anyone help how I can resolve this.

Kshitij Bajracharya
  • 811
  • 2
  • 14
  • 37
Coder atpace
  • 49
  • 2
  • 7
  • 4
    Casting is not converting. – Kayaman Oct 18 '19 at 07:29
  • 2
    You cannot cast one class to another just because they have the same `simpleName`. It does not have sense. They should have the same `fully queslified name` or be connected by `subtyping` of some sort. – lotor Oct 18 '19 at 07:33
  • 1
    it's impossible. They are not identical, even if they happen to share the same attributes and methods. – Pawan Maurya Oct 18 '19 at 08:26
  • Can it be done by using Reflection ? – Coder atpace Oct 18 '19 at 08:47
  • 1
    @BadmashCoder Maybe, but a rule of thumb is: use Reflection wisely, and use it only as last resort. – MC Emperor Oct 18 '19 at 11:32
  • @BadmashCoder If your two eponymous classes are somehow related, your code should reflect that. See also [What is an interface in Java?](https://stackoverflow.com/questions/1321122/what-is-an-interface-in-java) – MC Emperor Oct 18 '19 at 11:38

0 Answers0