当前位置: 代码迷 >> J2SE >> 请教怎样对泛型类型实例化
  详细解决方案

请教怎样对泛型类型实例化

热度:73   发布时间:2016-04-24 13:41:14.0
请问怎样对泛型类型实例化?
用以下方法进行实例化会报错,请问怎样实例化??  
class   A <T>   {
    T   a;
    A()   {
                  a   =   new   T();
      }
}



------解决方案--------------------
你这是定义泛型类吧
------解决方案--------------------
不能这么用,通过构造方法的参数初始化吧
------解决方案--------------------
建议先google下资料。看看 <T> 到底表示什么意思。
------解决方案--------------------
构造泛型类型的实例
获取表示泛型类型的 Type 对象。下面的代码以两种不同方式获取泛型类型 Dictionary:一种方法使用 System.Type.GetType(System.String) 方法重载和描述类型的字符串,另一种方法调用构造类型 Dictionary<String, Example>(在 Visual Basic 中为 Dictionary(Of String, Example))的 GetGenericTypeDefinition 方法。MakeGenericType 方法需要泛型类型定义。


Dim d1 As Type = GetType(Dictionary(Of ,))


Dim d2 As New Dictionary(Of String, Example)

Dim d3 As Type = d2.GetType()
Dim d4 As Type = d3.GetGenericTypeDefinition()

Type d1 = typeof(Dictionary<,>);

// You can also obtain the generic type definition from a
// constructed class. In this case, the constructed class
// is a dictionary of Example objects, with String keys.
Dictionary<string, Example> d2 = new Dictionary<string, Example>();
// Get a Type object that represents the constructed type,
// and from that get the generic type definition. The 
// variables d1 and d4 contain the same type.
Type d3 = d2.GetType();
Type d4 = d3.GetGenericTypeDefinition();

构造一组用于替换类型参数的类型变量。数组必须包含正确数目的 Type 对象,并且顺序和对象在类型参数列表中的顺序相同。在这种情况下,键(第一个类型参数)的类型为 String,字典中的值是名为 Example 的类的实例。

Dim typeArgs() As Type = _
{ GetType(String), GetType(Example) }
Type[] typeArgs = {typeof(string), typeof(Example)};

调用 MakeGenericType 方法将类型变量绑定到类型参数,然后构造类型。

Dim constructed As Type = _
d1.MakeGenericType(typeArgs)
Type constructed = d1.MakeGenericType(typeArgs);

使用 CreateInstance 方法重载来创建构造类型的对象。下面的代码在生成的 Dictionary<String, Example> 对象中存储 Example 类的两个实例。

Dim o As Object = Activator.CreateInstance(constructed)
object o = Activator.CreateInstance(constructed);

------解决方案--------------------
感觉有点像Template了...
------解决方案--------------------
like 5#
这样调用
Java code
A<String> a = new A<String>("123");System.out.println(a.a);
------解决方案--------------------
不能new T()的
------解决方案--------------------
new 后面要跟构造方法名 是 new a()
------解决方案--------------------
A<String> a = new A<String>("123");
System.out.println(a.a);
  相关解决方案