Is there a way to get the class of an object that ...
# getting-started
j
Is there a way to get the class of an object that extends another object? For example,
Copy code
class Car: Vehicle()
...
getObjectChildClass(Car())
...
fun getObjectChildClass(obj: Vehicle) {
     // From here I want the to know if it's a Car or some other class that extends vehicle, like Truck.
}
or would I simply have to store a list of such classes, and loop through and check if its one of them?
l
obj::class.java.name
j
I noticed that property but it gives it as a string, which poses more problems on turning that string into an actual reference to the class. I figured out a work-around.
l
Which is?
j
I made an Enum that gets stored in the child object. I dont get the class directly from this but with some other changes (too much to explain), I'm able to do what I needed.
t
Why don't you just use a type check? What do you want to do with the class? https://kotlinlang.org/docs/reference/typecasts.html
j
I'm storing various child objects in a
HashMap<DataType, Packet>
. I'm using the DataType enum beacuse I have X amount of classes that might be stored as a Packet. Originally I had a helper method,
classToDataType()
, which I wanted to give a class, and then have it return the data type. I could've done type check but then I would have to make a list of possible classes and check every one. Given that it's part of caching I dont want to have to loop a potentially large list every time.
t
You could use `sealed class`es in a when statement.