There is a generic interface:
public interface IMyQueue<T> {
//...
}
and there is a generic class implementing it:
public class MyQueueImp<T> implements IMyQueue<T> {
//...
}
I want the implementation to have a factory method: a public static method getInstance
that instantiate an object for that generic class.
public class MyQueueImp<T> implements IMyQueue<T> {
public static IMyQueue getInstance() {
///....
}
}
So I can call it like this:
IMyQueue<Integer> queue = MyQueueImpl.getInstance();
The problem is within this static methods there is not access to generic T
:
MyPriorityQueueImpl.this' cannot be referenced from a static context
I'm wondering how should I do this?
Your factory method is static, so it knows nothing of the actual argument for T
. You would have to declare it on the method itself:
public static <U> IMyQueue<U> getInstance() {
return new MyQueueImp<U>(); //or whatever instantiation you have
}
Side note: it's a bit strange to have an IMyQueue
factory in one specific implementation of IMyQueue
. Perhaps a better place to put this factory method is a separate class, or you could even put it in IMyQueue
itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.