[英]Java Generic Method basics (reflection)
我试图正确地理解如何使用泛型。 我整个上午都在搜索它,但是当教程开始添加多个泛型值或使用我仍在努力的非常抽象的术语时,我感到困惑。
我仍在学习,因此欢迎任何一般性建议,但是我想特别指出返回泛型类的方法的语法。
例如考虑:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.