0

问题:如果类构造函数包含继承类参数,如何正确创建类反射?我有:

interface Car {}
class SportCar implement Car{}
class CarService {
  public CarService(String str, Car car) {
     ...
  }
}

但是,当我尝试这样做时:

Class c = Class.forName("vbspring.model.CarService");
Class[] paramTypes = {String.class, SportCar.class};
Constructor constr = c.getDeclaredConstructor(paramTypes);

它抛出:java.lang.NoSuchMethodException: vbspring.model.CarService.(java.lang.String, vbspring.model.SportCar)

PS我的.xml文件:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="carService" class="model.CarService">
        <constructor-arg value="Car Rental Service"/>
        <constructor-arg ref="sportCar"/>
        <property name="startCar"/>
    </bean>

    <bean id="sportCar" class="model.SportCar"/>

</beans>

编辑:我尝试编写类似我自己的 Spring Framework 的东西。我不仅必须创建属于 Car 层次结构的类,因此我尝试编写可以创建任意类型的类的通用方法。我不能写:Class[] paramTypes = {String.class, Car.class};

我必须写一些通用的东西,比如:

paramTypes[index++] = obj.getClass();

其中 obj - 是解析器从 .xml 中提取的 SportCar 或 Car bean

4

1 回答 1

0

错误java.lang.NoSuchMethodException: vbspring.model.CarService.(java.lang.String, vbspring.model.SportCar)表明您没有构造函数,例如:

public CarService(String, SportCar)

你没有。你有:

public CarService(String, Car) {

将您的代码更改为

Class c = Class.forName("vbspring.model.CarService");
Class[] paramTypes = {String.class, Car.class}; // the constructor takes Car not SportsCar
Constructor constr = c.getDeclaredConstructor(paramTypes);

然后,当您调用构造函数以获取新实例时,您可以传递一个SportsCar实例或任何其他Car实例。

constr.newInstance("sport", new SportsCar());
// or
constr.newInstance("a jeep", new Jeep());
// or
constr.newInstance("long car", new Limousine());

假设JeepLimousine实施Car

于 2013-04-15T17:57:53.607 回答