试试这样的东西
private <T> void setModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
}
如果你想得到列表回来,然后
private <T> ArrayList<T> getModel(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
编辑
演示如何对 ARRAYLIST 使用泛型类型的完整示例
具有 main 方法和泛型方法的测试器类
public class Tester {
private <T> ArrayList<T> getModels(Class<T> type) {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = (ArrayList<Data>) t.getModels(Data.class);
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = (ArrayList<Magic>) t.getModels(Magic.class);
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
在没有参数的情况下使用相同的东西的另一种可能性,因为我们不在方法中使用它
public class Tester {
private <T> ArrayList<T> getModel() {
ArrayList<T> arrayList = new ArrayList<T>();
return arrayList;
}
public static void main(String[] args) {
Data data = new Data(12, "test_12");
Magic magic = new Magic(123, "test_123");
Tester t = new Tester();
ArrayList<Data> datas = t.getModel();
datas.add(data);
for(Data data2 : datas) {
System.out.println(data2);
}
ArrayList<Magic> magics = t.getModel();
magics.add(magic);
for(Magic magic2 : magics) {
System.out.println(magic2);
}
}
}
模型类(数据)
public class Data {
private Integer id;
private String name;
public Data() {
}
public Data(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}
模型类(魔术)
public class Magic {
private Integer id;
private String name;
public Magic() {
}
public Magic(Integer id, String name) {
super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Data [" + (id != null ? "id=" + id + ", " : "") + (name != null ? "name=" + name : "") + "]";
}
}