首页 > 解决方案 > 泛型作为构造函数的参数

问题描述

我正在查看一个包含多个条目的代码,如下所示:

open class PersonFinder: Finder<Long, Person>(Person::class.java)
open class CompanyFinder: Finder<Long, Company>(Company::class.java)
open class DeviceFinder: Finder<Long, Device>(Device::class.java)

我想要一种更通用的方法,如下所示:

open class GenericFinder<T>: Finder<Long, T>(T::class.java)

但语法无效,因为 T::class.java 不能用作那里的参数。有什么方法可以让我以惯用的方式完成这项工作吗?

标签: genericskotlin

解决方案


我想我找到了解决方案:

open class GenericFinder<T>(type: Class<T>) : Finder<Long, T>(type)

推荐阅读