0

这个问题可能听起来令人困惑,老实说确实如此。我会尽力向我解释自己。

我正在创建一个方法,使用Java Reflection, 从给定类创建一个新对象并将其添加到List. 我的课是:火车。所以我的列表是List<Train>,但我从反射创建的对象中得到的是一个通用/普通对象。我的意思是,只有方法的对象toStringhashCode等等,而不是火车类的方法。因此,我需要将 Object 转换为 Train 类型的 Object。就像是:Train t = (Train) Object;

我被卡住的地方是该方法知道类,因为它带有一个参数,但我不知道如何转换它......嗯,我知道令人困惑。让我们举一个实际的例子。

班列:

public class Train {
private String name;
private int id;
private String brand;
private String model; 


public Train(String name, int id, String brand, String model)
{
    this.name = name;
    this.id = id;
    this.brand = brand;
    this.model = model;
}

public void setName(String name) {
    this.name = name;
}

public void setId(int id) {
    this.id = id;
}
(... more sets and gets)
}

我的方法(这里我在评论中解释了我卡住的地方):

public class NewMain {

public static void main(String[] args) {
    try {

                List<Train> list = new ArrayList<>();
                qqCoisa(list, Train.class, String.class, int.class);


    } catch (ClassNotFoundException ex) {
        System.out.println("Erro ClassNotFound -> "+ex.getMessage());
    } catch (NoSuchMethodException ex) {
        System.out.println("Erro NoSuchMethod - > "+ ex.getMessage());
    } catch (InstantiationException ex) {
        System.out.println("InstantiationException -> "+ ex.getMessage());
    } catch (IllegalAccessException ex) {
        System.out.println("IllegalAcessException -> "+ ex.getMessage());
    } catch (IllegalArgumentException ex) {
        System.out.println("IllegalArgumentException -> "+ ex.getMessage());
    } catch (InvocationTargetException ex) {
        System.out.println("Invocation Target Exception -> "+ ex.getMessage());
    }
}



public static void qqCoisa(List list, Class theClass, Class _string, Class _int) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{

    Constructor ctor = theClass.getConstructor(_string, _int, _string, _string);
    ctor.setAccessible(true);
    Object obj = ctor.newInstance("Train XPTO", 1, "Volvo", "FH12");


    // here is where I'm stuck, In this case I know it is a Train object so 
    // I cast it 'manually' to Train but the way I want to do is to make it 
    // cast for the same type of theClass that comes in the parameter.
    // Something like: theClass t = (theClass) obj;
    Train t = (Train) obj; 
    list.add(t); 

    System.out.println("T toString -> "+t.toString());
    System.out.println("Obj toString -> "+obj.toString());
}

如果我没有解释自己,请告诉我,我会进一步解释。

4

1 回答 1

1

可以如下声明 qqCoisa 方法:

public static <T> void qqCoisa(List<T> list, Class<String> _string, Class<Integer> _int) throws Exception
{
    ....
    ....

    @SuppressWarnings("unchecked")
    T t = (T) obj;
    list.add(t);

    ....
    ....
}

这是一个适用于 T 类型参数的泛型方法。一旦将参数类型声明为 T,Class 参数就是多余的,因为方法声明带有此信息。

于 2013-10-12T04:23:06.963 回答