简体   繁体   English

将字符串转换为 Java 中的 Generics 类型参数

[英]Converting String to Generics type argument in Java

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?这可能吗?

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 .我假设,在您创建了typeNameSet之后,代码将 go 开启。
About generics.关于 generics。 After the code is compiled, all information about generics is gone.代码编译完成后,关于 generics 的所有信息都消失了。 During runtime, when you've created the type of typeName , for the program, it's just gonna be an Object.在运行时,当你为程序创建了typeName的类型时,它只是一个 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. Generics 只是为了在编程时很清楚,您正在处理哪种类型的Object ,这样您就不需要强制转换并且编译器可以检查这通常是否有效。
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.如果您想稍后在 object 上调用某些内容,则需要使用反射,除非您提供了一些更精确的信息,即您正在处理的是Object

The easiest thing to put there is just Object .最简单的就是Object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM