Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doing without instanceof

 
John Coleman
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can I use generics or covariant return types to somehow avoid using iinstanceof here:

target.setField(source.getField(field));

In this case both the setter and getter demand field to be a subclass of type Field, rather than of Field as presently.

These are types and methods from a third party library, I cannot change the implementations.

TIA
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even with Java 1.0, you don't need to use instanceof in this case - just cast to the type that is required.

If you can't change the code of the methods, generics or covariant return types can't help you, or so it seems to me.
 
John Coleman
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
Even with Java 1.0, you don't need to use instanceof in this case - just cast to the type that is required.

If you can't change the code of the methods, generics or covariant return types can't help you, or so it seems to me.


Unfortunately I think your comment above is right, and I have to code:

if (field instanceof StringField) {
target.setField((StringField) field);
} else
if (field instanceof DoubleField) {
target.setField((DoubleField) field);
} else
if (field instanceof IntField) {
target.setField((IntField) field);
} else
if (field instanceof CharField) {
target.setField((CharField) field);
} else
if (field instanceof BooleanField) {
target.setField((BooleanField) field);
} else
if (field instanceof UtcDateOnlyField) {
target.setField((UtcDateOnlyField) field);
} else
if (field instanceof UtcTimeOnlyField) {
target.setField((UtcTimeOnlyField) field);
} else
if (field instanceof UtcTimeStampField) {
target.setField((UtcTimeStampField) field);
}

But that's inefficient to execute and maintain.

Something like this looks good, but since there is no setField<T>, not possible.

setField(field.getClass(), field, target);

static <T> void setField(Class<T> clazz, Field field, FieldMap target) {
target.setField(clazz.cast(field));
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic