Как инстанцировать ArrayList<?> и добавить объект посредством отражения с Java?

4 ответа

Should be something pretty close to:

Object list = field.getType().newInstance();

Method add = List.class.getDeclaredMethod("add",Object.class);

add.invoke(list, addToAddToList);

Hope this helps.

8
ответ дан 9 December 2019 в 22:38
поделиться

It seems like the real issue here is going from XML to java objects. If that is the case (and since you are new to Java), a better solution than rolling your own may be to investigate existing technologies such as:

3
ответ дан 9 December 2019 в 22:38
поделиться

In java generics are just syntax sugar and they do not exist in runtime. This is why you cannot programmatically create generic objects in runtime. Try to create non generic list and cast (however I am not sure as my experience is limited with GWT).

0
ответ дан 9 December 2019 в 22:38
поделиться

You'll have to create a raw typed List (i.e. with no type parameters).

List subs = deserialize( ... );

If you were to set the raw typed List on your class directly:

obj.setSubObjects(subs); //You'll get an "unchecked cast" warning at compile time

Although the compiler will emit a warning, it is legal Java code and will run just fine at runtime because the parameter-type information is lost (i.e. at runtime, there is no difference between a List and a List). You can of course set it reflectively also.

0
ответ дан 9 December 2019 в 22:38
поделиться
Другие вопросы по тегам:

Похожие вопросы: