在java中实例化泛型类型 [英] Instantiating generics type in java

查看:104
本文介绍了在java中实例化泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


重复:Java泛型为什么这不起作用



重复:在Java中实例化泛型类


我想在java中创建泛型类型的对象。请建议我如何才能达到相同的效果。



注意:这可能看起来是一个微不足道的泛型问题。但我敢打赌,事实并非如此。 :)



假设我有类声明:

  public class Abc< T> {
public T getInstanceOfT(){
//我想创建一个T的实例并返回相同的结果。


$ / code $ / pre

解决方案

  public class Abc< T> {
public T getInstanceOfT(Class< T> aClass){
return aClass.newInstance();




$ b你必须添加异常处理。 p>

你必须在运行时传递实际的类型,因为它不是编译后的字节代码的一部分,所以没有明确提供它就无法知道它。 p>

Duplicate: Java generics why this won’t work

Duplicate: Instantiating a generic class in Java

I would like to create an object of Generics Type in java. Please suggest how can I achieve the same.

Note: This may seem a trivial Generics Problem. But I bet.. it isn't. :)

suppose I have the class declaration as:

public class Abc<T> {
    public T getInstanceOfT() {
       // I want to create an instance of T and return the same.
    }
}

解决方案

public class Abc<T> {
    public T getInstanceOfT(Class<T> aClass) {
       return aClass.newInstance();
    }
}

You'll have to add exception handling.

You have to pass the actual type at runtime, since it is not part of the byte code after compilation, so there is no way to know it without explicitly providing it.

这篇关于在java中实例化泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆