#generics

1 messages · Page 1 of 1 (latest)

uneven ridge
echo vault
#

What are you trying to do?

uneven ridge
#

i have a generic class

#

that im trying to wrap

#

but i need generic type

echo vault
#

Unsafe casts arent inherently bad. If you keep them internal then you can assure safety.

uneven ridge
#

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

echo vault
#

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.

uneven ridge
#

i would still need a generic

#

since im returning T inside one of the class methods

echo vault
#

Is there a good reason why you dont just use Gson?

uneven ridge
#

I could use TypeToken but as I said i would still need to use the generic type