我试图正确理解如何使用泛型。我整个早上都在搜索它,但当教程开始添加多个通用值或使用我仍在努力解决的非常抽象的术语时,我感到很困惑。
我仍在学习,因此欢迎任何一般性建议,但我想具体弄清楚返回泛型类的方法的语法。
例如考虑:
public class GenericsExample4 {
public static void main(String args[]) {
Car car;
Truck truck;
car = buy(Car.class, 95);
truck = buy(Truck.class, 45);
}
// HELP HERE!
public static <T extends Vehicle> T buy(Class<T> type, int topSpeed) {
// create a new dynamic class T . . . I am lost on syntax
return null; // return the new class T. I am lost on the syntax here :(
}
}
interface Vehicle {
public void floorIt();
}
class Car implements Vehicle {
int topSpeed;
public Car(int topSpeed) {
this.topSpeed = topSpeed;
}
@Override
public void floorIt() {
System.out.println("Vroom! I am going " + topSpeed + " miles per hour");
}
}
class Truck implements Vehicle {
int topSpeed;
public Truck(int topSpeed) {
this.topSpeed = topSpeed;
}
@Override
public void floorIt() {
System.out.println("I can only go " + topSpeed + " miles per hour");
}
}
有人可以指出如何将这个通用方法结合在一起吗?
最佳答案
一般情况下,您不能调用 new
运算符。您可以做的是使用反射,假设您知道构造函数的参数。例如,假设每辆车都有一个构造函数,它采用 int
最高速度:
public static <T extends Vehicle> T buy(Class<T> type, int topSpeed) {
try {
return type.getConstructor(Integer.TYPE).newInstance(topSpeed);
} catch (Exception e) { // or something more specific
System.err.println("Can't create an instance");
System.err.println(e);
return null;
}
}
关于Java 泛型方法基础知识(反射),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302536/