创建编译时未知的类的实例 [英] Create instance of a class not known at compile time
本文介绍了创建编译时未知的类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个抽象类:
I have an abstract class:
public abstract class Room {
}
以及在编译时未知的继承类,如:
and inherited classes that are not known at compile time like:
public class MagicRoom extends Room {
public MagicRoom(){
System.out.println("Creating a MagicRoom.");
}
public String magic = "";
}
或:
or:
public class Dungeon extends Room {
public Dungeon(){
System.out.println("Creating a Dungeon");
}
public String keeper = "";
}
我有一个要从中创建这些类的实例的类:
I have a class that I will be creating instances of these classes from:
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,所以如果我尝试使用属于继承类的字段,则会得到一个异常:
makeRoom is my attempt to create a class inherited from Room which type I don''t know at compile time, but I''m not sure what to put as its return type instead of Room. Because makeRoom returns a Room I get an exception if I try to use a field that belongs to an inherited class:
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";
}
}
在此先感谢.
Thanks in advance.
推荐答案
我需要使该方法通用,在此处获得关于StackOverflow的答案:
解决方案 [
I needed to make the method generic, got the answer on StackOverflow here:
the solution[^]
For reference, here is the code:
public static T makeRoom(Class roomClass)
throws IllegalArgumentException, InstantiationException,
IllegalAccessException, InvocationTargetException,
SecurityException, NoSuchMethodException{
// This is enough, if you have 0-arg constructor in all your subclasses
return roomClass.newInstance();
}
这篇关于创建编译时未知的类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文