决定在执行时实例化哪个子类
我有一个带有一些子类的 Forum
类,并将子类名称与所有其他字段一起作为字符串字段存储在数据库中。当我检索该对象时,我希望它是同一类的实例。我可以做很多 if-else 语句来查找要调用的子类构造函数,但它不容易扩展。
我找到了这个解决方案,但感觉有点脏:
public static Forum createForum(int forumId, String kind) {
try {
Class cls = Class.forName("forum."+kind);
Constructor ct = cls.getConstructor(Integer.TYPE, String.class);
Object retobj = ct.newInstance(forumId, kind);
return (Forum) retobj;
}
catch (Throwable e) {
System.err.println(e);
}
return null;
}
有更好的解决方案吗?
谢谢。
I have a Forum
class with some subclasses, and I store the subclass name as a String field on a database along all other fields. When I retrieve the object, I want it to be an instance of the same class it was. I could do a lot of if-else statements to find which subclass constructor to call, but it wouldn't be easily extensible.
I have found this solution, but it feels somehow dirty:
public static Forum createForum(int forumId, String kind) {
try {
Class cls = Class.forName("forum."+kind);
Constructor ct = cls.getConstructor(Integer.TYPE, String.class);
Object retobj = ct.newInstance(forumId, kind);
return (Forum) retobj;
}
catch (Throwable e) {
System.err.println(e);
}
return null;
}
Is there any better solution?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种替代方法是为
Forum
类创建一个“工厂对象”接口,然后使用工厂实例填充映射以创建每个子类。如果不同的子类构造函数需要不同的参数,事情会变得更加困难。但这对于您的反思解决方案来说也会有问题。
从长远来看,使用 ORM(如 Hibernate)可能会提供更优雅的解决方案。
One alternative is to create a "factory object" interface for your
Forum
classes, and then populate a map with factory instances to create each of the subclass.Things would be more difficult if different subclass constructors required different arguments. But that would also be problematic for your reflective solution.
In the long term, using an ORM (like Hibernate) is likely to give a more elegant solution.
我认为您正在寻找的是 对象序列化
(该页面有点广告密集,但它有一些很好的信息。谷歌搜索“java对象序列化”会返回很多信息)
Oracle教程在这里:http://java.sun.com/developer/technicalArticles/Programming/serialization/
I think what you're looking for is Object Serialization
(That page is a little advertising heavy, but it has some good info. Googling "java object serialization" will return lots of info)
The Oracle tutorial is here: http://java.sun.com/developer/technicalArticles/Programming/serialization/
是的,有一个替代方案 - 对象关系映射 (ORM),它可以为您完成此操作 - 以及更多其他功能。 Java 的 ORM 框架包括 Hibernate 和 DataNucleus。
Yes, there is an alternative - Object-Relational Mapping (ORM), which does this for you - and much more besides. ORM frameworks for Java include Hibernate and DataNucleus.