-1

I would like to write a Generic program that receives a String from the user and creates a container of that type using reflection. This should be something on the lines of

public static void main(String []args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the type you want to use ");
    String typeName = scanner.nextLine();
    Set<????> mySet = new HashSet(); 
}

What should I put in the ???? part? Is this possible?

Shaharg
  • 804
  • 10
  • 19
  • "What should I put in the ???? part?" What do you want to do with `mySet`? – Andy Turner Jan 28 '21 at 17:11
  • 1
    Does this answer your question? [Java generics type erasure: when and what happens?](https://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens) – Charlie Armstrong Jan 28 '21 at 17:11
  • 1
    In short, something like `Set` becomes just `Set` at runtime. The type argument is only syntax sugar. It's just something that the compiler looks at and stops you from doing stupid things. – Charlie Armstrong Jan 28 '21 at 17:13

1 Answers1

1

I'm not really sure, what you try to achieve. I assume, the code will go on after you've created that Set of typeName.
About generics. After the code is compiled, all information about generics is gone. During runtime, when you've created the type of typeName, for the program, it's just gonna be an Object.
Generics is just so that while programming, it's clear, which type of Object you are handling with, so that you don't need to cast and the compiler can check that this generally works.
If you want to call something on the object later, you'll need to use reflection unless you made some more precise information, which kind of Object you're dealing with.

The easiest thing to put there is just Object.

Rainer Jung
  • 484
  • 5
  • 19