Java: Creating a subclass object from a parent object

前端 未结 11 2307
攒了一身酷
攒了一身酷 2020-12-09 14:28

Newbie Java question. Say I have:

public class Car{
  ...
}

public class Truck extends Car{
  ...
}

Suppose I already have a Car object, h

11条回答
  •  伪装坚强ぢ
    2020-12-09 15:17

    I know this is an OLD question, but I hate to leave out dated answers when things have improved.

    Using JSON is much easier. Convert it to JSON and back again as child.

    Here is an Android Kotlin Example.

        val gson = Gson()    
        val childClass = gson.fromJson(
            gson.toJson(parentObject), 
            object: TypeToken(){}.type
        ) as ChildObject
    

    I think in Java it would be basically.

    Gson gson = new Gson()
    ChildObject child = (ChildObject) gson.fromJson(
        gson.toJson(parentObject),
        TypeToken(){}.getType()
    ) 
    

    And you're done, no messiness, just simple json in, json out. If you don't have gson, I'm sure you have other json options available to you.

    It's a WHOLE lot cleaner and faster than doing reflection and all that craziness.

提交回复
热议问题