Java 泛型方法基础(反思)

Java Generic Method basics (reflection)

我正在尝试正确理解如何使用泛型。我整个上午都在搜索它,但是当教程开始添加多个通用值,或者使用我仍在努力解决的非常抽象的术语时,我感到困惑。

我还在学习,所以欢迎任何一般性建议,但我想具体弄清楚返回泛型的方法的语法 class。

例如考虑:

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;
    }
}