问题描述
基本上我用一个泛型创建一个函数,泛型类型是一个抽象类型,我需要实例。这段代码会更清楚地解释它:
public< T extends AbstractRow> foo(){//不,我实际上没有命名函数foo
ArrayList< T> arr = new ArrayList< T>();
arr.add(new T(...)); //无法实例化抽象类的对象
}
基本上我想执行T扩展AbstractRow但不是抽象本身
我意识到你不能实例化抽象类,所以我想在解决方法上提出建议或者其他一些方法可以让我模仿创建泛型类型的对象的行为。
提前致谢
您的主要问题不是您正在使用抽象类 - 在评论中发布的建议将会很有用。更大的问题是,你试图直接实例化一个泛型类型(阅读: new T()
) - 简而言之,你不能在Java中执行,因为。
也就是说,总是有一个解决方法:
/ ** @param clazz你想要实例化的子类* /
public< T extends AbstractRow> foo(Class< T> clazz){
ArrayList< T> arr = new ArrayList< T>();
arr.add(clazz.newInstance); //实例化给定子类的新实例
}
用法:
抽象类Test1 {}
class Test2 extends Test1 {}
$ b $ class Test< T> {
public static< T extends Test1> T foo(Class< T> clazz){
T toReturn = null;
try {toReturn = clazz.newInstance(); catch(Exception e){};
返回到返回;
public static void main(String [] args){
Test1 t1 = t.foo(test2.class);
System.out.println(t1.getClass()); //打印class pkgname.test2
}
}
Hey guys was hoping you could help me out.
Basically I am creating a function with a generic type and that generic type is an abstract type which I need to instantiate. This code will explain it more clearly:
public <T extends AbstractRow> foo(){//no I did not actually name the function foo
ArrayList<T> arr=new ArrayList<T>();
arr.add(new T(...)); //cant instantiate objects of abstract class
}
Basically I want to enforce "T extends AbstractRow but is not Abstract itself"
I realize you can't instantiate abstract classes, so I'd like a suggestion on a workaround or some other method that would allow me to mimic the behavior of creating an object of a generic type.Thanks in advance
Your main issue isn't that you're working with an abstract class - in which case the suggestions posted in the comments would be useful. The bigger problem is that you're trying to instantiate a generic type directly (read: new T()
) - which, simply put, you can't do in Java because of type erasure.
That said, there's always a workaround:
/**@param clazz the subclass you want to instantiate */
public <T extends AbstractRow> foo(Class<T> clazz) {
ArrayList<T> arr = new ArrayList<T>();
arr.add(clazz.newInstance); //instantiate new instance of given subclass
}
Usage:
abstract class Test1 {}
class Test2 extends Test1{ }
class Test<T> {
public static <T extends Test1> T foo(Class<T> clazz) {
T toReturn = null;
try{ toReturn = clazz.newInstance(); } catch (Exception e) { };
return toReturn ;
}
public static void main(String[] args) {
Test1 t1 = t.foo(test2.class);
System.out.println(t1.getClass()); //prints "class pkgname.test2"
}
}
这篇关于使用泛型类型实例化抽象类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!