Java 泛型方法基础知识(反射)

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

有人可以指出如何将这个通用方法结合在一起吗?

最佳答案

一般情况下,您不能调用 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/

相关文章:

java - JFileChooser:设置名称文本字段未启用

java - 从 Grails 运行外部 Groovy 脚本时出现 UTF-8 编码错误

generics - 泛型结构的构造函数中出现 "Expected type parameter"错误

swift - 让 Swift 泛型玩转重载函数

Java 反射 : Get concrete type of implemented generic interface

java:从类中查找项目名称

java - 在 java 中调用 System.exit() 的确切目的是什么

java - 将基本数据源与连接池数据源混合在一起 : when to call close()?

generics - 具有变量类型的 F# 函数

java - 如何获取@XmlElement注释的值