r*******w 发帖数: 121 | 1 怎样能够得知一个object的class呢?
就是说我有一个object
我要on the fly new 一个deep copy of it...
so i have to call the related constructor...
but I want the implementation quite generic...
i know i can do
if obj instanceof Class1
then new_obj=new Class1(obj)
else if obj instanceof Class2
then new_obj=new Class2(obj)
etc...
any other more elegant solution? |
m******t 发帖数: 2416 | 2
You can call obj.getClass() to get the Class object for obj.
(quite a tongue twister isn't it)
But you'll have to make sure each of the classes you need to copy
has a default constructor, otherwise you'll still end up checking
classes.
【在 r*******w 的大作中提到】 : 怎样能够得知一个object的class呢? : 就是说我有一个object : 我要on the fly new 一个deep copy of it... : so i have to call the related constructor... : but I want the implementation quite generic... : i know i can do : if obj instanceof Class1 : then new_obj=new Class1(obj) : else if obj instanceof Class2 : then new_obj=new Class2(obj)
|
r*******w 发帖数: 121 | 3 then call newInstance of the Class object?
sounds good ah...
thanks~~~
【在 m******t 的大作中提到】 : : You can call obj.getClass() to get the Class object for obj. : (quite a tongue twister isn't it) : But you'll have to make sure each of the classes you need to copy : has a default constructor, otherwise you'll still end up checking : classes.
|