Java - 将 class 传递给函数
Java - Passing a class to a function
我正在实施序列化,并试图使一切尽可能模块化。从文件中读取对象时,我试图只使用一个函数将所有内容传递给 ArrayList 或类似的东西。目前我正在做这样的事情:
public static ArrayList<Class1> ReadClass1(String fileName) {
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<Class1>();
while (1 != 2) {
p.add((Class1) in.readObject());
}
} catch (Exception e) {
;
}
return p;
}
但是,我想阅读其他 类,比方说 Class2
或 Class3
,现在我正在复制粘贴代码并编辑所有内容“ Class1”到“Class2”。有没有办法像这样传递我想使用的特定类型?
public static ArrayList<myClass> ReadProducts(String fileName, myClass) { //where myClass is a class
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<myClass>();
while (1 != 2) {
p.add((myClass) in.readObject());
}
} catch (Exception e) {
;
}
return p;
}
这样我就可以为不同的 类?
重用该函数
您可以使用 java Generics。请找到以下代码:
public static <T> ArrayList<T> ReadProducts(String fileName, Class<T> t) {
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<T>();
while (1 != 2) {
p.add(t.cast(in.readObject()));
}
} catch (Exception e) {
;
}
return p;
}
我正在实施序列化,并试图使一切尽可能模块化。从文件中读取对象时,我试图只使用一个函数将所有内容传递给 ArrayList 或类似的东西。目前我正在做这样的事情:
public static ArrayList<Class1> ReadClass1(String fileName) {
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<Class1>();
while (1 != 2) {
p.add((Class1) in.readObject());
}
} catch (Exception e) {
;
}
return p;
}
但是,我想阅读其他 类,比方说 Class2
或 Class3
,现在我正在复制粘贴代码并编辑所有内容“ Class1”到“Class2”。有没有办法像这样传递我想使用的特定类型?
public static ArrayList<myClass> ReadProducts(String fileName, myClass) { //where myClass is a class
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<myClass>();
while (1 != 2) {
p.add((myClass) in.readObject());
}
} catch (Exception e) {
;
}
return p;
}
这样我就可以为不同的 类?
重用该函数您可以使用 java Generics。请找到以下代码:
public static <T> ArrayList<T> ReadProducts(String fileName, Class<T> t) {
ArrayList p = null;
try {
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(fileName)));
p = new ArrayList<T>();
while (1 != 2) {
p.add(t.cast(in.readObject()));
}
} catch (Exception e) {
;
}
return p;
}