gpt4 book ai didi

java - 如何将对象转换为类对象(作为参数传入) - Java

转载 作者:行者123 更新时间:2023-12-01 14:01:16 26 4
gpt4 key购买 nike

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

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

我遇到的问题是该方法知道该类,因为它包含在参数中,但我不知道如何转换它......我知道这很令人困惑。让我们展示一个实际的例子。

类(class)列车:

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());
}

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

最佳答案

您可以按如下方式声明 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 参数就多​​余了,因为方法声明携带了此信息。

关于java - 如何将对象转换为类对象(作为参数传入) - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19330451/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com