开发者

Generic object with private constructor

开发者 https://www.devze.com 2023-03-15 02:43 出处:网络
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 w

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

精彩评论

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