Ros*_*ala 0 java generics inheritance object instance
我有一些子类,其中所有子类都由一个公共父类扩展.
我想要的是父类中的具体方法,该方法应该返回给定类类型的新对象.
这是我试过的.
class Vehicle {
public <T> T get(Class<T> type){
//return new T();
}
}
class Car extends Vehicle {
}
class Van extends Vehicle {
}
Run Code Online (Sandbox Code Playgroud)
以上get(...)
方法
return new T();
Run Code Online (Sandbox Code Playgroud)
语句给出了编译错误,
需要意外类型:
找到的类:类型参数T.
我不能直接创建子类的对象,比如
new Car();
Run Code Online (Sandbox Code Playgroud)
由于某些原因.可以有任意数量的子类,因此get()
每个子类中的重写方法也不是一种选择.任何的想法?
您可以Class
使用实例化对象Class.newInstance()
.
public <T> T get(Class<T> type) throws InstantiationException, IllegalAccessException {
return type.newInstance();
}
Run Code Online (Sandbox Code Playgroud)
但是这个类必须有一个无参数的构造函数; 它可能会引发异常.
归档时间: |
|
查看次数: |
102 次 |
最近记录: |