gpt4 book ai didi

java - 创建编译时未知的类的实例

转载 作者:行者123 更新时间:2023-12-03 02:40:13 24 4
gpt4 key购买 nike

我有一个抽象类:

public abstract class Room {

}

以及编译时未知的继承类,例如:

public class MagicRoom extends Room {

public MagicRoom(){
System.out.println("Creating a MagicRoom.");
}

public String magic = "";
}

或者:

public class Dungeon extends Room {

public Dungeon(){
System.out.println("Creating a Dungeon");
}

public String keeper = "";
}

我有一个类,我将从中创建这些类的实例:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class MazeGame {

public static Room makeRoom(Class roomClass)
throws IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException{

Constructor c = roomClass.getConstructor();
return c.newInstance();

}

}
makeRoom 是我尝试创建一个从 Room 继承的类,该类在编译时我不知道其类型,但我不确定将什么作为其返回类型而不是 Room。因为 makeRoom 返回一个 Room,所以如果我尝试使用属于继承类的字段,则会出现异常:

import java.lang.reflect.InvocationTargetException;

public class FactoryTest {

public static void main(String[] args)
throws IllegalArgumentException, SecurityException,
InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException{

MazeGame game = new MazeGame();

Room magicRoom = MazeGame.makeRoom(MagicRoom.class);

/*
* Exception in thread "main" java.lang.Error: Unresolved compilation problem:
* magic cannot be resolved or is not a field
*/

magicRoom.magic = "a";

}
}

最佳答案

使该方法通用:

public static <T extends Room> T makeRoom(Class<T> roomClass) 
throws IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException{

// This is enough, if you have 0-arg constructor in all your subclasses
return roomClass.newInstance();
}

然后像这样调用它:

MagicRoom magicRoom = MazeGame.makeRoom(MagicRoom.class);  

关于java - 创建编译时未知的类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632979/

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