gpt4 book ai didi

Java 从泛型 Class 对象获取方法

转载 作者:行者123 更新时间:2023-12-02 06:47:41 25 4
gpt4 key购买 nike

我有一个如下所示的方法,其中此类包含一个对象列表,到目前为止可以传入 2 个不同的类。

public class DataTableEntity {
List<Objects> objectContainer;

public void setLinks(Class cls){
for(Object obj : objectContainer){
//the cls variable will hold what type of object it is
//so I need to somehow say if its a 'dog' then the obj I am going through is a dog
// and the method is dog.getName else it might be cat and cat.getCatName etc.
}
}

此函数被告知列表具体是什么,然后在发送到客户端之前应正确格式化该列表中对象的属性。不同的对象对这些属性有不同的 setter 和 getter 名称。因此,我需要以某种方式获取通用 Class 对象,看看它到底是什么类型,这样我就可以知道要使用什么方法,“.getAbc/.setAbc”或“.getXyz/.setXyz”。

这可能吗?

最佳答案

像这样吗?

public class DataTableEntity {
List<Objects> objectContainer;

// The Objects know already which Class they are, no need to pass it
public void setLinks() {
for(Object obj : objectContainer) {
if(obj instanceof ClassA) {
ClassA a = (ClassA)obj;
a.doSomething();
}
else if(obj instanceof ClassB) {
ClassB b = (ClassB)obj;
b.doSomethingElse();
}
// and so on ...
}
}
}

通用接口(interface)将使代码变得更好,因为您不必检查所有不同的类。但我不知道这是否适合你的情况

关于Java 从泛型 Class 对象获取方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18445577/

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