我想使用反射为泛型类创建一个类。
有人可以告诉我如何创建它吗?
我有
public class SomeClass<T>
{
....
}
我需要使用反射为SomeClass<T>
创建一个类。
答案 0 :(得分:9)
使用MakeGenericType方法:
Type myParameterizedSomeClass = typeof(SomeClass<>).MakeGenericType(typeof(MyParameter));
ConstructorInfo constr = myParameterizedSomeClass.GetConstructor(typeof(ConstrParamType1),typeof(ConstrParamType2));
答案 1 :(得分:0)
您是否需要使用在运行时创建新类的反射来实例化现有类? 如果是前者:
Class<?> c = Class.forName("SomeClass");
SomeClass<String> sc = (SomeClass<String>)c.newInstance();
如果是后者,请查看Javassist。没有试过但它看起来很容易使用。 我假设你使用的是Java。