繁体   English   中英

如何使以下代码更好?

[英]how can I make the following code better?

我想使以下代码更好,但不能有一个好主意。 有什么办法解决这个问题?

我只是创建一个Android项目,并使用greenDAO greendao按Class创建表。

for (Field field : fields) {
    fieldName = field.getName();
    // we don't need this.
    if ("serialVersionUID".equals(fieldName)) {
        continue;
    }
    type = field.getType();
    // primary key, just auto increment.
    if ("id".equals(fieldName)) {
        entity.addIdProperty().autoincrement();
        continue;
    }
    // other fields
    /*
     * this is the problem what I want to solve.
     * I thought it's too bad to read and have a bad looking.
     */
    if (type.equals(String.class)) {
        entity.addStringProperty(fieldName);
    }else if (type.equals(Integer.class)) {
        entity.addIntProperty(fieldName);
    }else if (type.equals(Double.class)) {
        entity.addDoubleProperty(fieldName);
    }else if (type.equals(Float.class)) {
        entity.addFloatProperty(fieldName);
    }else if (type.equals(Long.class)) {
        entity.addLongProperty(fieldName);
    }else if (type.equals(Byte.class)) {
        entity.addByteProperty(fieldName);
    }else if (type.equals(Short.class)) {
        entity.addShortProperty(fieldName);
    }else if (type.equals(Boolean.class)) {
        entity.addBooleanProperty(fieldName);
    }else if (type.equals(Character.class)) {
        entity.addStringProperty(fieldName);
    }else if (type.equals(Date.class)) {
        entity.addDateProperty(fieldName);
    }
}

可以使用==而不是.equals来比较Class对象,因为每个类只有一个实例。

有时需要像这样的嵌套if语句序列来找到正确的Class对象,这显然很丑陋(有关此示例,请参阅Arrays.deepToString的源代码)。

还有其他解决方案涉及Map ,或者打开type.getSimpleName() ,但是我个人会坚持使用简单的解决方案,即使它花了很多时间。

Java 8解决方案:创建一个“加法方法”的静态Map ,其中每种可能的属性类型都将与相应的lambda关联:

static final Map<Class<?>, BiConsumer<Entity, String>> ADDERS = new IdentityHashMap<>();
{{ 
    ADDERS.put(String.class,  Entity::addStringProperty);
    ADDERS.put(Integer.class, Entity::addIntegerProperty);
    //...
}}

然后,对于每个field

ADDERS.get(type).accept(entity, field.getName());

您可以使用更多反射。

String typeStr = type.getSimpleName();
switch(typeStr) {
    case "Integer": typeStr = "Int"; break;
    case "Character": typeStr = "String"; break;
}
Method m = enttity.getClass().getMethod("add" + typeStr + "Property", String.class);
m.invoke(entity, fieldname);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM