#generics
1 messages · Page 1 of 1 (latest)
What are you trying to do?
Unsafe casts arent inherently bad. If you keep them internal then you can assure safety.
to make that class work
public class ObjectDataFile<T> {
private final Path path;
private final Class<T> clazz;
public ObjectDataFile(@NotNull final Path path, @NotNull final Class<T> clazz) {
this.path = path;
this.clazz = clazz;
}
inside another class
this.objectFile = new ObjectDataFile<Map<Integer, ItemStack>>(this.path,
Map.class); // Error Map.class is not the right type correct class type is Class<Map<Integer, ItemStack>>
i need to somehow get the Map<Integer, ItemStack> class object
luckily im using an object with that specific type
the problem that the object class has type erasure problems since it returns Class<capture ? extends Map> and not Class<Integer, ItemStack> via .getClass()
i cant construct the generic class without it
Ah i see. This is not so easy. Gson has solved this using so called TypeTokens.
public class ObjectDataFile {
private final Path path;
private final Type type;
public ObjectDataFile(Path path, Type type) {
this.path = path;
this.type = type;
}
}
ObjectDataFile dataFile = new ObjectDataFile(path, new TypeToken<Map<String, Integer>>() {}.getType());
But this eliminates the generic type making type safe methods harder.
Serializing generics is a real hustle because of the type erasure.
Is there a good reason why you dont just use Gson?
I could use TypeToken but as I said i would still need to use the generic type