Redian新闻
>
Generics应该怎么得到它的class?
avatar
Generics应该怎么得到它的class?# Java - 爪哇娇娃
d*i
1
一般的普通的class,可以通过MyClass.class得到,但是如果有Generics的情况,由于
type erasure,就没法得到它的class,比如我想用List.class,就会报错,
但是有些class method只接受这样的input argument:
public void foo(Class class)
如果我想传入一个List的类的话,怎么办?没法用
foo(List.class)
avatar
g*g
2
Depends on whether you have control on the API, you may pass in a
GenericEntity.
avatar
d*i
3
多谢,如果是第三方库没有办法改method呢?比如这个:
public static JAXBContext newInstance(Class... classesToBeBound)
我没法传入List.class

【在 g*****g 的大作中提到】
: Depends on whether you have control on the API, you may pass in a
: GenericEntity.

avatar
f*n
4
List.class就行了。只有一个List class object。

【在 d****i 的大作中提到】
: 一般的普通的class,可以通过MyClass.class得到,但是如果有Generics的情况,由于
: type erasure,就没法得到它的class,比如我想用List.class,就会报错,
: 但是有些class method只接受这样的input argument:
: public void foo(Class class)
: 如果我想传入一个List的类的话,怎么办?没法用
: foo(List.class)

avatar
g*g
5
you can always write a listofstr class, ugly but works anyway.

【在 d****i 的大作中提到】
: 多谢,如果是第三方库没有办法改method呢?比如这个:
: public static JAXBContext newInstance(Class... classesToBeBound)
: 我没法传入List.class

avatar
g*m
6
There is a solution,
create a generic list wrapper to wrap your String List, whatever List, and
JAXB always unmarshall xml message to the wrapper, and from this wrapper
object, you can get the wrapped List object.
I have used this approach a lot in my projects, it works well.
http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-
avatar
d*i
7
Thanks. This is a nice solution. I think it is similar to goodbug's solution
but it uses a generic List in the wrapper class.

wrapper

【在 g******m 的大作中提到】
: There is a solution,
: create a generic list wrapper to wrap your String List, whatever List, and
: JAXB always unmarshall xml message to the wrapper, and from this wrapper
: object, you can get the wrapped List object.
: I have used this approach a lot in my projects, it works well.
: http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-

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