vendredi 16 mars 2018

type safe Parsing in java

I am implementing a parser in java.

The data I am parsing has different types of records. Let's say these are record type A, B, C, ... These records have some common attributes. so I am thinking of interface Record that all records A, B, C.. will implement. The data in file will be like:

A
B
B
C
C
C
...
X
Y
Z

I am thinking to have iterator of records. but it won't be type-safe. since I can only have

interface Record {
   String getRecordName();
   RecordType recordType();
}
class A implements Record {
    @Override
    String getRecordName() {...}
    // record type 'A' specific methods/fields here
}
class B implements Record{
    @Override
    String getRecordName() {...}
    // record type 'B' specific methods/fields..
}
class Parser implements Iterable<Record> {

    boolean hasNext() {...}
     // user has to examine record type and cast
    Record next() { ...} 
}

Any way to get around this problem? Could visitor pattern be useful here?

Edit: Since what I have here is a stream of records (of different types), I would still like composition features. like normal stream has (like map, filter, takeWhile, etc)

Aucun commentaire:

Enregistrer un commentaire