dimanche 14 juin 2020

Conditionally cast a generic class using IF-ELSE and receive the casted object outside it

I have a generic class defined as

*public class EventHolder<T>
{
private typeCode;
private var2;
private T encryptedPayload
}*

Here encryptedPayload can be different class types carrying data from different incoming events. typeCode tells us the class/event carried by encryptedPayload.

The requirement is to extract the data from encryptedPayload/event and insert it into a table.

The traditional way would be to use a nested IF-ELSE statement to route the processing of every event to a different eventWriter class.

However I am seeing if the insertion could be done through just one class.

This I beleive can be possible if we can cast the eventHolder class conditionally based on typeCode in a way like below:

*if (typeCode='Approved')
  { EventHolder<Approved> event = incomingEvent;}
else
{ EventHolder <Declined> event = incomingEvent;}*

and then someway have the casted EventHolder object available outside the IF-ELSE block with the way it gets casted within.

However since 'event' is local to IF-ELSE it doesn't get available outside it. And if it gets declared outside, a re-declaration or casting within IF-ELSE isn't allowed.

So, do you think we could find a way to cast the EventHolder class within the IF-ELSE block conditionally based on what 'typeCode' has and be able to receive the casted EventHolder object outside it.

Any help towards thiswould be highly appreciated.

Aucun commentaire:

Enregistrer un commentaire