函数Java从泛型类对象获取方法
我有一个如下的方法,其中这个类包含一个对象列表,到目前为止,可以传入两个不同的类
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名称。所以我需要以某种方式获取泛型类对象,看看它到底是什么类型的类,这样我就可以知道使用什么方法,“.getAbc/.setAbc”或“.getXyz/.setXyz”
这可能吗
# 1 楼答案
你听说过声明的实例吗
它允许您检查对象是否是类或其子类的实例,并返回布尔值
比如:
# 2 楼答案
像这样
一个通用的接口将使代码变得更好,因为您不必检查所有不同的类。但我不知道你的情况是否可能