我创建了以下类:
public class Abuser {
<T extends Spam> List<T> createSpam() {
List<T> lst = new ArrayList<>();
T s = new T();
s.prepareAd();
lst.add(s);
// the above is done unknown number of times
return lst;
}
}
用于这样的类:
public class Spam {
void prepareAd() {}
}
public class WildSpam extends Spam {}
public class MildSpam extends Spam {}
以下列方式:
Abuser a = new Abuser();
Lost<WildSpam> wSpam = a.createSpam();
List<MildSpam> mSpam = a.createSpam();
如何轻松搞定这项工作?
答案 0 :(得分:-1)
Java应该知道必须创建哪些对象。您必须将一些参数传递给您的方法以通知它。
像这样:
public class Abuser {
<T extends Spam> T createSpam(T a) {
T s = null;
try {
Class cls = Class.forName(a.getClass().getName());
s = (T) cls.newInstance();
s.prepareAd();
// the above is done unknown number of times
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
}
像这样使用:
Abuser a = new Abuser();
WildSpam wSpam=new WildSpam();
wSpam=a.createSpam(wSpam);
MildSpam mSpam = new MildSpam();
mSpam=a.createSpam(mSpam);
此代码适用于一个对象而非对象列表。