使用泛型在 Groovy 中传递 class 的实例

Passing an instance of a class in Groovy using generics

圣杯:2.4.4 Groovy:2.4.1 Java : 1.8u40

Windows 7

我正在尝试制作一个基于泛型的控制器,我的团队成员可以根据需要对其进行扩展。

刚刚在 Groovy 中使用泛型解决了这个问题 ()

我现在 运行正在尝试传递 class.

的 Grails 控制器中的以下问题

TeamCotroller:

class TeamController extends BaseController<Team> {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    TeamController() {
        super(Team)
    }

    /*
    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Team.list(params), model:[teamInstanceCount: Team.count()]
    }
    */
    /*
    def show(Team teamInstance) {
       respond teamInstance
    }
    */
    /*
    def create() {
        respond new Team(params)
    }
    */

    /* More default CRUD methods cut out for now */
}

通用控制器: class 基地控制器 {

    private final Class<T> clazz

    BaseController(Class<T> clazz) {
        this.clazz = clazz
    }

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond clazz.list(params), model:[instanceCount: clazz.count()]
    }

    // TODO: Figure this out
    def show(Team instance) {
        respond instance
    }
}

show(Team instance) 方法中,我已将 Team 替换为 Class<T>T 以尝试通过 [=40= 获取传递给它的实例] 但当我 运行 在调试模式下时,它甚至似乎根本没有命中该方法。需要做什么才能将实例传递给控制器​​?

--edit-- 添加例外 2015-03-06 15:56:36,400 [http-bio-8090-exec-5] ERROR errors.GrailsExceptionResolver - MissingPropertyException occurred when processing request: [GET] /test-list/team/show/1 No such property: instance for class: TeamController. Stacktrace follows: Message: No such property: instance for class: TeamController

-- 编辑 -- 添加控制器代码

直接将实例传递给方法的参数时似乎不起作用,但在使用id参数时确实可以正常工作,如下所示:

grails-app/controllers/BaseController.groovy

abstract class BaseController<T> {

  private final Class<T> clazz

  BaseController() {}

  BaseController(Class<T> clazz) {
    this.clazz = clazz
  }

  def index(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    respond clazz.list(params), model:[instanceCount: clazz.count()]
  }

  def show(Long id) {
    def instance = clazz.get(id)
    respond instance
  }
}

grails-app/controllers/TeamController.groovy

class TeamController extends BaseController<Team> {

    TeamController() {
        super(Team)
    }
}

那么您应该能够毫无问题地访问 /team/show/1.?{format} 端点。

我设置了一个示例项目here来演示。