0

In the code below:

    public class AvroReader<T> {

    public AvroReader(Class type, File packetFile) throws IOException{
            reader = new DataFileReader<>(packetFile,
                    new ReflectDatumReader<T>(ReflectData.get().getSchema(type)));
    }
}

I'd like to do away with the field "type" in the constructor because type=T.class. If only the compiler accepted getSchema(T.class) !

One suggestion was to use:

Class<T> cls = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

I get this error:

java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
fodon
  • 4,565
  • 12
  • 44
  • 58
  • I don't think you can eliminate the `type` parameter in this situation due to erasure. See [this answer](http://stackoverflow.com/a/1886680/658907). – matts Mar 13 '13 at 23:49

1 Answers1

0

You need to retrieve the class of your generic parameter using the black magic voodoo below :

Class<T> persistentClass = (Class<T>) (getClass().getGenericSuperclass());

Then you can transform your code like this

Schema schema = ReflectData.get().getSchema(persistentClass);

Actually the black voodoo magic line is getting by reflection the type of the generic argument used when instantiating the class. You have to do it based on instances because you don't know the type of your parameter when you are defining of your class (as generics are a syntactic sugar and are lost at runtime).

benzonico
  • 10,635
  • 5
  • 42
  • 50
  • That didn't work but this did:Class persistentClass = (Class) (getClass().getGenericSuperclass()); – fodon Mar 13 '13 at 20:41
  • This would only work if you were creating a subclass of `AvroReader` that specified an explicit `T` in the `extends`-clause. – matts Mar 13 '13 at 23:43