来自字符串的通用类型声明
Generic type declaration from string
我有一个 Class 测试Class{}
我需要从字符串输入
为此 class 创建实例
TestClass<"StringValue"> obj = new TestClass<"StringValue">()
如何实现?
您肯定误解了 Java 中泛型的用途。很快,泛型使 types 成为参数,但不是精确值。 Take a look at documentation to get more. 引自本文:
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
如果您想在 class 实例化期间定义一些特定值,pass it to constructor as parameter。
更新:
OP 指出他在原始问题中提到的字符串值是 class 名称的字符串表示形式。在这种情况下,泛型将无济于事,因为 Java 泛型只是编译时特性,您不能使用在运行时计算的值来参数化 class。您可以根据这个问题中描述的名称创建 Class
实例:Getting Class type from String,但它仍然不能用作泛型参数。
这是做不到的,字符串 "" 和所有基本数据类型,如 int
double
等都不能在泛型中使用。
但你可以这样做:
Foo<String>
或 Foo<Integer>
等...
如果这不能满足您的需求,那么您可以创建一个class并存储您需要的所有数据,如下所示:
public class Foo {
String stringValue;
int intValue;
...
}
并像这样使用它:
public TestClass<Foo> {
...
}
更新:
您也可以将数据作为 String
然后您可以将其解析为任何其他类型的数据,例如 int
、float
等
例如:
LinkedList<String> list = new LinkedList<>();
list.add("12");
int intValue = Integer.parseInt(list.get(0));
这就是我想做的,
Class clazz = Class.forName(classnameAsString);
clazz.newInstance(); // created object from name of class
重温我的老问题 :P。感谢其他回答,这些回答在 Java 中介绍了我一些其他的东西 :)
我有一个 Class 测试Class{}
我需要从字符串输入
TestClass<"StringValue"> obj = new TestClass<"StringValue">()
如何实现?
您肯定误解了 Java 中泛型的用途。很快,泛型使 types 成为参数,但不是精确值。 Take a look at documentation to get more. 引自本文:
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
如果您想在 class 实例化期间定义一些特定值,pass it to constructor as parameter。
更新:
OP 指出他在原始问题中提到的字符串值是 class 名称的字符串表示形式。在这种情况下,泛型将无济于事,因为 Java 泛型只是编译时特性,您不能使用在运行时计算的值来参数化 class。您可以根据这个问题中描述的名称创建 Class
实例:Getting Class type from String,但它仍然不能用作泛型参数。
这是做不到的,字符串 "" 和所有基本数据类型,如 int
double
等都不能在泛型中使用。
但你可以这样做:
Foo<String>
或 Foo<Integer>
等...
如果这不能满足您的需求,那么您可以创建一个class并存储您需要的所有数据,如下所示:
public class Foo {
String stringValue;
int intValue;
...
}
并像这样使用它:
public TestClass<Foo> {
...
}
更新:
您也可以将数据作为 String
然后您可以将其解析为任何其他类型的数据,例如 int
、float
等
例如:
LinkedList<String> list = new LinkedList<>();
list.add("12");
int intValue = Integer.parseInt(list.get(0));
这就是我想做的,
Class clazz = Class.forName(classnameAsString);
clazz.newInstance(); // created object from name of class
重温我的老问题 :P。感谢其他回答,这些回答在 Java 中介绍了我一些其他的东西 :)