根据类型创建不同的对象 [英] Create different objects depending on type

查看:318
本文介绍了根据类型创建不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一个名为列类型的数据库表。在我的数据库列的每一行我要创建取决于类型的对象。目前,我使用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

这篇关于根据类型创建不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆