我在返回键入的列表时遇到了困难。由于某种原因,它会作为原始列表返回,但我真的想要输入键入的列表。
它与类抽象有关。通过在类上添加/删除abstract关键字,我的List从raw变为typed,反之亦然。看起来它因为抽象而向下传播我的泛型?
public abstract class Notice<T> {
public List<Contact> contacts;
public List<Contact> getContacts()
{
return this.contacts;
}
}
public class Contact {
}
public class Service {
public Service(Notice notice) {
// ! Would like to use List<Contact> here, as I defined in Notice !
List contacts = notice.getContacts();
}
}
我该如何解决这个问题,为什么会这样呢?我尝试过Java Generics FAQ等。
更新的代码; 的 FacebookMessengerService
public class FacebookMessengerService extends MessengerService<FacebookNotice> {
public void send(FacebookNotice notice)
{
//
// ERROR occurs here:
// "Type mismatch: cannot convert from element type Object to Contact"
//
// Also, hovering over it tells me to be just a rawtyped List instead of List<Contact>
//
for (Contact contact : notice.getContacts())
{
// ..
}
}
}
MessengerService
public abstract class MessengerService<T extends Notice> implements IMessengerService<T> {
}
IMessengerService
public interface IMessengerService<T extends Notice> {
public void send(T notice);
}
FacebookEventInvitationNotice
public class FacebookEventInvitationNotice extends FacebookNotice<EventInvitation> {
public FacebookEventInvitationNotice(EventInvitation trigger) {
super(trigger);
}
}
FacebookNotice
public abstract class FacebookNotice<T extends Trigger> extends Notice<T> {
public static FacebookMessengerService service = new FacebookMessengerService();
public FacebookNotice(T trigger) {
super(trigger);
}
public void send()
{
service.send(this);
}
}
通知
public abstract class Notice<T extends Trigger> implements INotice<T>
{
public List<Contact> contacts = new ArrayList<Contact>();
public T trigger;
public Notice(T trigger)
{
this.trigger = trigger;
}
public void addContact(Contact contact)
{
this.contacts.add(contact);
}
public List<Contact> getContacts()
{
return this.contacts;
}
}
INotice
public interface INotice<T extends Trigger> {
public void send();
}
EventInvitation
public class EventInvitation extends Trigger {
private Event event;
public EventInvitation(Event event)
{
this.event = event;
}
public Event getEvent()
{
return this.event;
}
}
触发
public class Trigger {
public List<Notice> notices = new ArrayList<Notice>();
}
答案 0 :(得分:3)
你需要完全通用:
public class Service {
public Service(Notice<?> notice) {
List<Contact> contacts = notice.getContacts();
}
}
答案 1 :(得分:0)
将我的代码更改为:
public class FacebookMessengerService extends MessengerService<FacebookNotice<?>> {
public void send(FacebookNotice<?> notice)
{
for (Contact contact : notice.getContacts())
{
}
}
}
我的问题似乎已经解决了!不过,我看不出FacebookNotice
和FacebookNotice<?>
之间的区别如何强迫我的List<Contact>
成为原型列表?