avatar
继续问土问题# Java - 爪哇娇娃
r*w
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?
avatar
m*t
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)

avatar
r*w
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.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。