Singleton con argumento genérico
Frecuentes
Visto 93 veces
0
How can I create my instance?
I always get compilation errors.
Description Resource Path Location Type Cannot make a static reference to the non-static type COMPONENT ComponentManager.java
package component;
public class ComponentManager<COMPONENT extends Component> {
private static ComponentManager<COMPONENT> instance = new ComponentManager<COMPONENT >();
private ComponentManager() {
}
public static ComponentManager<?> getInstance() {
return instance;
}
}
2 Respuestas
1
Your syntax is wrong on the declaration and instantiation. Create 'instance' like this:
private static ComponentManager<? extends Component> instance = new ComponentManager< >();
Respondido el 26 de Septiembre de 13 a las 19:09
It should and does work for me, at least for compilation. Java 7 added limited type inference capabilities. docs.oracle.com/javase/7/docs/technotes/guides/language/… - david007
@daveed007. Ah! sorry. It was fault on my side. It compiles fine. - Rohit jainista
0
Pon el new ComponentManager()
línea dentro del getInstance()
method call the constructor if instance
is null, otherwise return instance
.
public class ComponentManager {
private static ComponentManager instance;
private ComponentManager() {
}
public static ComponentManager getInstance() {
if (instance != null) {
} else {
instance = new ComponentManager();
}
return instance;
}
}
Respondido el 26 de Septiembre de 13 a las 19:09
I wanna do my getInstance() without if conditional. - Everton
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java generics singleton or haz tu propia pregunta.
If you get compilation errors and want our help, please consider posting the error messages in their entirety. - Hovercraft Full Of Eels
You appear to be possibly missing import statements for one, unless you have your own Component class. - Hovercraft Full Of Eels
I take from your code that you want N singletons, each for a subclass of
Component
? If that is the case it won't work due to borrado tipo. - SJuan76