包/类名可以是函数参数吗?

时间:2013-10-08 08:37:15

标签: java android function package

我有以下代码:

import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;

...
builder = newBuilder(id, Email.CONTENT_ITEM_TYPE, bUpdate);
if (bPref) {
    builder.withValue(Email.TYPE, Email.TYPE_CUSTOM);
    builder.withValue(Email.LABEL, "PREF");
} else if (iType != -1) {
    builder.withValue(Email.TYPE, iType);
}
builder.withValue(Email.DATA, value);
ops.add(builder.build());

builder = newBuilder(id, Phone.CONTENT_ITEM_TYPE, bUpdate);
if (bPref) {
    builder.withValue(Phone.TYPE, Phone.TYPE_CUSTOM);
    builder.withValue(Phone.LABEL, "PREF");
} else if (iType != -1) {
    builder.withValue(Phone.TYPE, iType);
}
builder.withValue(Phone.DATA, value);
ops.add(builder.build());

builder = ...
...

这些块非常相似,我想为它们编写一个函数。

例如:

void build(xxx name) {
  ...
  if (bPref) {
    builder.withValue(name.TYPE, name.TYPE_CUSTOM);
    builder.withValue(name.LABEL, "PREF");
  } else if (iType != -1) {
    builder.withValue(name.TYPE, iType);
  }
  builder.withValue(name.DATA, value);
  ops.add(builder.build());
}

...
build(Email);
build(Phone);
build(...);

或者有没有办法将这些重构为函数?

1 个答案:

答案 0 :(得分:0)

这是我能弄清楚如何使它成为一个函数的唯一方法:

void build(String itemType, String fieldType, int typeCustom, String label, String data) {
}

...
build(Email.CONTENT_ITEM_TYPE, Email.TYPE, Email.TYPE_CUSTOM, Email.LABEL, Email.DATA);
build(Phone.CONTENT_ITEM_TYPE, Phone.TYPE, Phone.TYPE_CUSTOM, Phone.LABEL, Phone.DATA);
build(Website.CONTENT_ITEM_TYPE, Website.TYPE, Website.TYPE_CUSTOM, Website.LABEL, Website.DATA);

它并不像我预期的那样简洁,但比原来的重复块更好。