Java Generic Method基础知识(反射)

时间:2015-07-08 19:59:49

标签: java generics reflection instantiation

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

我还在学习,所以欢迎任何一般性建议,但我想特别指出返回泛型类的方法的语法。

例如考虑:

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

有人可以指出如何将这种通用方法联系在一起吗?

1 个答案:

答案 0 :(得分:5)

您不能一般致电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;
    }
}