根据类型创建不同的对象根据、对象、不同、类型

2023-09-06 17:21:37 作者:哥不帅但很坏

我有一个包含一个名为列类型的数据库表。在我的数据库列的每一行我要创建取决于类型的对象。目前,我使用if else语句为:

I have a database table that contains a column named type. For every row in my database column I have to create an object depending on the type. At the moment I use if else statements for that:

if (type.equals("object1")){
    Object1 object1 = new Object1();
}
else if (type.equals("object2")){
    Object2 object2 = new Object2();
}

有点更好的办法是使用一个枚举,作为类型的数量是有限的,但有没有可能让一个对象的创建依赖于字符串的值?

Somewhat nicer would be to use an enum, as the number of types is limited but is there a possibility to let the creation of an object depend on the value of the String?

我愿意比我想可能解决以另一种方式我的问题的建议。

I'm open to suggestions that might solve my problem in another way than I am trying to.

推荐答案

您可以使用

Object o = Class.forName(type).newInstance();

如果你有一个int和两个字符串作为你需要的参数。

If you have an int and two Strings as arguments you need.

Object o = Class.forName(type)
                .getConstructor(int.class, String.class, String.class)
                .newInstance(intValue, string1, string2);

另一种可能性是使用工厂方法

Another possibility is to use factory methods

Object o = getClass().getMethod("create_" + type).invoke(null);

static Object1 create_object1() {
     return new Object1(/* with args */);
}

static Object2 create_object2() {
     return new Object2(/* with other args */);
}

但最灵活的方法可能是使用一个开关

but the most flexible approach may be to use a switch

Object o;
switch(type) { // in Java 7
    case "object1": o = new Object1(); break;
    case "object2": o = new Object2(); break;

什么是Java中8。

What would be more elegant is using closures in Java 8.

http://cr.openjdk.java.net /~briangoetz/lambda/lambda-state-4.html

 
精彩推荐