Skip to content

faq 19431474

Billy Charlton edited this page Sep 5, 2018 · 2 revisions

Checking the type of a typed Id

by Johan W. Joubert on 2014-10-01 10:39:44


Maybe this is related to `', but I couldn't make it work. I do not want to convert from one Id  to another. Rather, I have to check what the particular type of the Id is. The following is fine:

		Id<Link> linkId = Id.createLinkId("1");
 		Object o = linkId;

 		if(o instanceof Id<?>){
 			Id<?> someId = (Id<?>)o;
 		}

But I cannot check (o instanceof Id<Link>)

Unfortunately the someId object does not give me much to work from, i.e. I do not see any methods I can/should use. I am aware the generic types, like our new Id, is not reifiable (from http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ106 ), but I don't know if it is possible given that we have control over how the generics of Id is implemented?

My only solution currently is to do something like

		Id<Link> linkId = Id.createLinkId("1");
 		Object o = linkId;

 		Id<?> someId = null;
 		if(o instanceof Id<?>){
 			someId = (Id<?>)o;
 		}
 		@SuppressWarnings("unchecked")
 		Id<Link> newId = (Id<Link>) someId; 

Is that fine?


Comments: 1


Re: Checking the type of a typed Id

by Marcel Rieser on 2014-10-01 14:20:13

There is currently no way to get the type of the Id, although such a function could be added if really required (feel free to open an issue on JIRA for that). But there you (theoretically) could get any type back, depending on the Id object you have.

Best thing would be to never lose the type information in the source code, i.e. never having Id or Id<?> or Object.

If you just want to test for a limited set of types, you could do the following:

if (o instanceof Id) {
   Id id = (Id) o;
   if (id == Id.create(id, Link.class)) {
     log.info("It's a link id.");
   } else if (Id == Id.create(id, Node.class)) {
     log.info("It's a node id.");
   }
 }

Basically, it makes use of the fact that typed ids of the same type are the same object when the ids have the same "value". So, you can just create a new Id of a specific type with the same value, and compare on object identity.

Clone this wiki locally