java - 如何使用反射来执行泛型构造函数
问题描述
假设我有String type = "Integer"
例如,我在另一边有一个public class MyType<T>
带有构造函数的 apublic MyType(){}
我如何使用 java 反射 newInstance 方法以便能够执行以下操作:
public static MyType<?> create(String type){
return /*new MyType<Integer>() if type was "Integer", etc*/;
}
解决方案
您不需要“字符串类型”参数,您可以使用以下代码:
public static void main(final String[] args)
{
final MyType<Integer> myType1 = create();
myType1.v = 1;
final MyType<String> myType2 = create();
myType2.v = "1";
System.out.print(myType1);
System.out.print(myType2);
}
public static class MyType<T>
{
T v;
}
public static <K> MyType<K> create()
{
return new MyType<>();
}
推荐阅读
- architecture - 报告整合组成
- java - Spring Boot Rest根据参数调用
- python - SQLAlchemy 与额外列的多对多关系
- python - Python套接字未从服务器接收数据字节
- python - 带有正斜杠的 Starlette/FastApi 路由路径组件
- azure - 检查 Azure 数据工厂中 getmetadata 活动返回的文件计数
- c# - EF core 3 问题通过字符串到 npgsqlTime
- python - 无法在 Windows 7 中激活 virtualenv venv
- javascript - 按顺序分组 - JS
- html - 我正在尝试制作计时器,我想将这 3 个按钮放在圆圈中