代码之家  ›  专栏  ›  技术社区  ›  aggaton

泛型类类型中的引用值和调用方法

  •  0
  • aggaton  · 技术社区  · 7 年前

    我刚从C来到科特林。目前,我正在尝试设置一个类,该类接受两个可互换的泛型类型,该类的内部代码是spring服务端点。

    我从下面的内容开始,但是我似乎在引用请求体的参数以及调用方法的语法方面有问题,这些类型是通过类构造函数传入的。泛型和反射的语法似乎并不那么直截了当,我所挖掘的大多数Kotlin示例似乎都没有准确地涵盖我要做的事情(如果可能的话)。type1的对象实例将通过body参数传入,type2的对象实例应通过构造函数传入(语法可能不正确)。

    计划将其用作模板,以基于相同的基本代码但具有不同的请求和服务类来设置多个端点。

    非常感谢您的帮助。

    import org.springframework.beans.factory.annotation.Autowired
    import org.springframework.http.HttpStatus
    import org.springframework.http.ResponseEntity
    import org.springframework.web.bind.annotation.RequestBody
    import org.springframework.web.bind.annotation.RequestMapping
    import org.springframework.web.bind.annotation.RequestMethod
    import javax.validation.Valid
    
    open class Base <T1,T2>(t1: Class<T1>, t2: Class<T2>) {
    
      @Autowired
      var type1 = t1
    
      @Autowired
      var type2 = t2
    
      @ApiOperation(value = "API 1", response = myResponse::class)
      @ApiResponses(value = *arrayOf(
        ApiResponse(code = 200, message = "successful", response = CcdaResponse::class),
        ApiResponse(code = 405, message = "Invalid", response = Void::class)))
      @RequestMapping(
        value = "/myEndPoint",
        produces = arrayOf("application/json"),
        consumes = arrayOf("application/json"),
        method = arrayOf(RequestMethod.POST)
      )
    
      fun endpoint(
        @ApiParam(value = "Options", required = true)
        @Valid
        @RequestBody
        body: Class<T1>
      ): ResponseEntity<myResponse> {
        val r = myResponse()
        val response: ResponseEntity<myResponse>
        response = ResponseEntity(r, HttpStatus.OK)
        try {
    
          //payload
          val parameters = Parameters().apply {
            Id1 = type1::body.Id1.get()
            Id2 = type1::body.Id2.get()
            Id3 = type1::body.Id3.get()
            Id4 = type1::body.Id4.get()
            v = type1::body.v.get()
          }
          //Do stuff like calling method in class of type2 passed in
          val d = type2.getViewModel(parameters)
    
          r.status = "ok"
    
        } catch (e: Exception) {
          r.message = e.toString()
          r.status = "error"
        } finally {
        }
        return response
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Bryan    7 年前

    参数的类型在创建实例时通过类型参数传递(与Java相同)。因此,您确实需要传入类型本身,添加一个 Class

    我相信这就是你想要的(为了简洁起见省略了一些代码)。

    open class Base<T1, T2> (@Autowired var t2: T2) {
    
        @Autowired var type1: T1? = null
    
        fun endpoint(
            @ApiParam(value = "Options", required = true) @Valid @RequestBody
            body: T1
        ): ResponseEntity<MyResponse> {
            type1 = body
        }
    
    }
    

    Int String (用于 T1 T2 分别按以下方式。

    val t2 = "t2"
    val base = Base<Int, String>(t2)
    

    或者可以将 Base 使用指定的任何(或无)类型初始化。

    class SubBase(t2: String): Base<Int, String>(t2)