Here is my problem. I would like to have a class with a private constructor that can be created with more than one static method, exactly like Box.createHorizontalBox()
. Where it gets complicated is when this class uses generics.
Please, tell me how to do this prop开发者_如何转开发erly:
private WorkFlow(int _arrowSize) {
this.arrowSize = _arrowSize;
this.elements = new ArrayList<T>();
}
public static WorkFlow<T> createHorizontalWorkFlow<T>(int _arrowSize) {
WorkFlow<T> workFlow = new WorkFlow<T>(_arrowSize);
workFlow.vertical = false;
return workFlow;
}
This is not working: Eclipse underlines the int
from createHorizontalWorkFlow<T>(int _arrowSize)
and gives me the error Syntax error on token(s), misplaced construct(s)
Try this:
public static <T> WorkFlow<T> createHorizontalWorkFlow(int _arrowSize) {
WorkFlow<T> workFlow = new WorkFlow<T>(_arrowSize);
workFlow.vertical = false;
return workFlow;
}
You were pretty close. Just had the <T>
in the wrong place - you must declare the generic type before the return type.
精彩评论