James
James

Reputation: 746

Initialize generic data structure at runtime?

I have implemented a generic data structure that holds comparable objects (ints, floats, strings, etc.). The signature looks like

public class MyStruct<T extends Comparable<T>> 

And during runtime, I am presented with a string input that could represent any comparable data type.

How could I instantiate the data structure according to whatever type the input string represents? Or should I change the data structure to accommodate this kind of situation?

So if the input is "4", I would like to instantiate with

MyStruct<Integer> struct = new Struct<Integer>();

and if the input is "4.0",

MyStruct<Float> struct = new Struct<Float>();

and so on to support all comparable types.

Upvotes: 0

Views: 94

Answers (1)

sumitsu
sumitsu

Reputation: 1511

At runtime, there is no difference between MyStruct<Integer> and MyStruct<Float>; the type information is available at compile-time only, and thereafter is dropped due to type erasure.

You could implement methods in your class to manually perform type conversion and checking, if you wish, but I do not believe there is a way to adapt your class as written to use a type inferred at runtime.

Upvotes: 1

Related Questions