我为每个类使用一个 init 方法。
Spam[] spam1 = new Spam[13];
Spam[] spam2 = new Spam[7];
Spam[] spam3 = new Spam[5];
initSpamArray(spam1);
initSpamArray(spam2);
initSpamArray(spam3);
void initSpamArray (Object[] a) {
for (int i = 0, len = a.length; i < len; i++) {
a[i] = new Spam();
}
}
Ham[] ham1 = new Ham[13];
Ham[] ham2 = new ham[7];
Ham[] ham3 = new Ham[5];
initHamArray(ham1);
initHamArray(ham2);
initHamArray(ham3);
void initHamArray (Object[] a) {
for (int i = 0, len = a.length; i < len; i++) {
a[i] = new Ham();
}
}
是否可以定义一种“通用”方法来初始化任何类型的对象?
至少喜欢:
void initObjArray (Object[] a, <s.g. which suitable to transfer Class>) {
for (int i = 0, len = a.length; i < len; i++) {
a[i] = new <s.g. which suitable to transfer Class>();
}
}
我尝试了很多谷歌并使用 java 反射(Object.getClass();Constructor.newInstance();Class.newInstance())。然而我并没有成功。