Catch ClassCastException when the encountered type doesn't match the

expected type, and re-throw as FormatException.
This commit is contained in:
akwizgran
2011-07-20 15:07:17 +01:00
parent 30d7a0f916
commit 45b4bef348
4 changed files with 47 additions and 10 deletions

View File

@@ -31,7 +31,7 @@ class BundleReaderImpl implements BundleReader {
if(state != State.START) throw new IllegalStateException();
reader.addObjectReader(Tags.HEADER, headerReader);
reader.readUserDefinedTag(Tags.HEADER);
Header h = reader.readUserDefinedObject(Tags.HEADER);
Header h = reader.readUserDefinedObject(Tags.HEADER, Header.class);
reader.removeObjectReader(Tags.HEADER);
state = State.FIRST_BATCH;
return h;
@@ -53,7 +53,7 @@ class BundleReaderImpl implements BundleReader {
return null;
}
reader.readUserDefinedTag(Tags.BATCH);
return reader.readUserDefinedObject(Tags.BATCH);
return reader.readUserDefinedObject(Tags.BATCH, Batch.class);
}
public void finish() throws IOException {

View File

@@ -386,11 +386,10 @@ class ReaderImpl implements Reader {
throw new FormatException();
}
@SuppressWarnings("unchecked")
private <T> T readObject(Class<T> t) throws IOException,
GeneralSecurityException {
try {
return (T) readObject();
return t.cast(readObject());
} catch(ClassCastException e) {
throw new FormatException();
}
@@ -507,14 +506,12 @@ class ReaderImpl implements Reader {
if(readUserDefinedTag() != tag) throw new FormatException();
}
public <T> T readUserDefinedObject(int tag) throws IOException,
public <T> T readUserDefinedObject(int tag, Class<T> t) throws IOException,
GeneralSecurityException {
ObjectReader<?> o = objectReaders.get(tag);
if(o == null) throw new FormatException();
try {
@SuppressWarnings("unchecked")
ObjectReader<T> cast = (ObjectReader<T>) o;
return cast.readObject(this);
return t.cast(o.readObject(this));
} catch(ClassCastException e) {
throw new FormatException();
}