如何将Object转换为类Object(作为参数提供) - Java

时间:2013-10-12 04:12:02

标签: java reflection casting

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

我正在使用Java Reflection创建一个方法,从给定的类创建一个新对象并将其添加到List。 我的班级是:火车。所以我的列表是List<Train>,但我从Reflection创建的对象得到的是一般/普通对象。我的意思是,只有方法toStringhashCode等的对象而不是Train类方法。因此,我需要将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());
}

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

1 个答案:

答案 0 :(得分: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参数就是多余的,因为方法声明包含此信息。