public class Depot extends Item2
{
}
public class Ship extends Item2
{
}
abstract public class Item2
{
public static void loadFromStream(FileInputStream oos) throws IOException
{
return new whatToWriteHereToGetDEPOTorSHIP?
}
}
Depot o1 = Depot.loadFromStream(oos);
Ship o2 = Ship.loadFromStream(oos);
代码中的问题:如何从静态方法创建Ship或Depot的实例?根据仓库。或发货。
答案 0 :(得分:3)
abstract public class Item2 {
public static Item2 loadFromStream(FileInputStream oos) throws IOException {
try (ObjectInputStream ois = new ObjectInputStream(oos)) {
return (Item2) ois.readObject();
}
}
}
之后你需要施展。如果您想要描述静态调用,请在子类中创建它们:
public class Depot extends Item2 {
static Depot loadDepotFromStream(FileInputStream oos) {
return (Depot)loadFromStream(oos);
}
}
答案 1 :(得分:3)
你可以这样做:
public class Depot extends Item2
{
public static Depot loadFromStream(FileInputStream oos) throws IOException
{
return Item2.loadFromStream(oos, Depot::new);
}
}
public class Ship extends Item2
{
// ... similar here
}
abstract public class Item2
{
protected static <T extends Item2> T // notice the "protected"
loadFromStream(FileInputStream oos, Supplier<T> cons) throws IOException
{
T t = cons.get()
// ...common logic...
return t;
}
}
答案 2 :(得分:2)
如果不传递有关要创建的类的信息作为参数,则无法执行此操作。
编译器处理以下2个相同的调用
Depot.loadFromStream(oos);
Ship.loadFromStream(oos);
这个电话
Item2.loadFromStream(oos);
请注意FileInputStream
可以存储有关该对象的信息。在这种情况下,您需要根据此信息处理对象创建...(有些类在标准API中为您执行此操作。)
答案 3 :(得分:1)
你可以这样做......
package main;
import java.io.FileInputStream;
import java.io.IOException;
public class Exam {
public static void main(String[] args) throws Throwable {
Depot depot = (Depot)Depot.loadFromStream(null, Depot.class);
System.out.println(depot);
Ship ship = (Ship)Ship.loadFromStream(null, Ship.class);
System.out.println(ship);
}
}
class Depot extends Item2
{
}
class Ship extends Item2
{
}
abstract class Item2
{
public static Object loadFromStream(FileInputStream oos, Class c) throws IOException, Throwable
{
return c.newInstance();
}
}