0

I need to cast any Object into its related EObject. When I try to do it I get a ClassCastException. My question is it possible to cast an object into a EObject and if it is possible how can I do it.

Thanks

Baptiste Gousset
  • 251
  • 2
  • 16
  • http://stackoverflow.com/questions/2986951/can-you-cast-an-object-to-one-that-implements-an-interface-java –  Mar 15 '12 at 19:10
  • possible duplicate of [Can someone explain "ClassCastException" in Java?](http://stackoverflow.com/questions/907360/can-someone-explain-classcastexception-in-java) (all ClassCastExceptions from casting are due to the same cause) –  Mar 15 '12 at 19:11

2 Answers2

2

If you are getting this exception, then the instance in question is not an EObject. It means that you are trying to say it is an EOjbect when in fact it is not.

You do understand that casting is not a conversion process right? It doesn't 'make' your object an EObject, it simply 'reveals' it as one (if it is one).

Your exception will actually tell you what the object is that you are trying to cast to EObject (which you should have included in your question, btw).

Robin
  • 24,062
  • 5
  • 49
  • 58
1

EObjects are interfaces that describe their corresponding objects, but that are not of the same type of them. You cannot cast these. And really, you don't want to. As EObjects and their descendents described models, not your actual program.

Jochen
  • 2,277
  • 15
  • 22
  • They are of the same type as their implementers. For instance, an ArrayList is a List and is also a Collection, and can absolutely be cast as such. This should NOT be marked as the correct answer. – Robin Mar 16 '12 at 17:14
  • @Robin, EObjects are parts of the EMF framework in Eclipse (http://download.eclipse.org/modeling/emf/emf/javadoc/2.4.3/org/eclipse/emf/ecore/EObject.html). Your example has absolutely nothing to do with them, and leads to confusion where there should be none. – Jochen Mar 16 '12 at 19:26
  • I stand corrected. I haven't looked at EMF in about 5 years and never thought about the problem from that standpoint. We are in fact both correct, but unlike you I didn't address the EMF confusion that the OP had. My apologies for the downvote. – Robin Mar 19 '12 at 15:55