Is there an easy way to check if two classes implement a common interface? I am using IntelliJ, and calling a Java library (Elastic Java High Level REST Client) from some Kotlin code.
SearchHit
and GetResponse
classes both have getId()
and getSourceAsString()
methods. How can I know if they implement a common interface, so that I can mutualize my functions that take these objects as parameters ?
This is my code :
fun JsonAdapter<Descriptor>.fromHit(hit: SearchHit): Descriptor {
val descriptor = this.fromJson(hit.sourceAsString)
if (descriptor == null) {
throw BadFormatException("Json descriptorDeserializer returned a null value")
}
descriptor.descriptorId = hit.id
return descriptor
}
fun JsonAdapter<Descriptor>.fromResponse(response: GetResponse): Descriptor {
val descriptor = this.fromJson(response.sourceAsString)
if (descriptor == null) {
throw BadFormatException("Json descriptorDeserializer returned a null value")
}
descriptor.descriptorId = response.id
return descriptor
}
You can try the is
keyword in Kotlin to check if an object is an instance of some interfaces :
if (obj is MyInterface) {...}
Which is the Kotlin equivalent of the Java :
if (obj instanceof MyInterface) {
//...
}
During development with Intellij Idea
, we can quickly check classes
declaration by pressing Ctrl + B when the cursor is on the class name.
If you don't know which interface is implemented by your classes you can use the following code to get a list of these interfaces. You'll get a list of classes that you can compare do see if your objects share a common interface.
val obj = MyClass()
var interfaces = obj.javaClass.interfaces
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.