开发者

Generic object with private constructor

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜