listing28.5.java

来自「java 完全探索的随书源码」· Java 代码 · 共 50 行

JAVA
50
字号
/* * CarShop */import java.lang.reflect.*;public class CarShop {  Car carList[];  public CarShop( String[] carTypes ) {    // create a car of each specified type    carList = new Car[carTypes.length];    for ( int i=0; i<carTypes.length; i++ ) {      carList[i] = createCar(carTypes[i], new TireSpecification());    }  }  public Car createCar(String carName, TireSpecification tires) {    Car newCar = null;    try {      Object constructorParam[] = new TireSpecification[1];      constructorParam[0]= tires;      // get the class name for the car that you want      Class carClass = Class.forName(carName);      // create an array of Classes, and use this to      // array to find the constructor that you want      Class parameters[] = new Class[1];      parameters[0]= TireSpecification.class;      Constructor  con = carClass.getDeclaredConstructor(parameters);      // create a car instance for the carList      newCar = (Car)con.newInstance(constructorParam);    }    catch (Exception e) {      System.out.println("Error creating " + carName);    }    return newCar;  }  // supply names of the car types as command line arguments  public static void main( String args[] ) {    // create a car shop that contains the specified car types    CarShop shop = new CarShop( args );    for ( int i=0; i<shop.carList.length; i++ ) {      System.out.println( shop.carList[i] );    }  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?