1

假设我有一个数据库表,如:

Table Building
ID int (primary key)
title varchar

为了获取这个,我有一个 Java 类,例如:

class Building{
  private Integer ID;
  private String title;
  ...
}

(如果对您有帮助,请在您的想象中添加一些 JPA 注释)。

但是现在,根据实际的建筑,我想执行一些逻辑。

我的第一个想法是创建一个大开关/外壳,例如:

switch(building.getId()){
  case 1:
    BuildingA buildingLogic = new BuildingA(building);
    break;
  case 2:
    BuildingB buildingLogic = new BuildingB(building);
    break;
  ...
}

buildingLogic.doBuildingSpecificStuff();

但这将以无休止的开关/案例结束,“阅读”并不是很清楚。

我的下一个想法(已经被 Mark Elliot 的回答所涵盖)是将实际的类名称作为附加字段(BuildingClass)写入数据库,并使用一些(对我目前未知的)java 魔法,从building.getBuildingclass()字符串创建对象,但是我已经假设这会有一些缺点......

所以我想也许你们可以给我更多的想法或评论我的想法。

4

2 回答 2

2

假设你确实有类名,你可以使用反射来实例化一个新实例,尽管沿着这条路走下去会有一些安全和性能风险。

String className = "com.foo.bar.Baz";

// gets the actual class (might throw an Exception if the class doesn't exist)
Class<?> clazz = Class.forName(className);

// probably want to have some common interface these conform to, so
// let's assume you have one, you can test this is the right kind of class
CommonBuildingType buildingLogic = null;
if (CommonBuildingType.class.isAssignableFrom(clazz)) {
    // get the constructor to invoke (might throw if no match)
    Constructor constructor = clazz.getDeclaredConstructor(Building.class);

    // safe to cast, we checked above
    buildingLogic = (CommonBuildingType) constructor.newInstance(building);
} else {
    // throw an exception?
}
于 2013-08-24T22:17:27.420 回答
0

您应该使用hibernate来更复杂地实现它

于 2013-08-24T22:19:43.023 回答