Home > Blockchain >  Put objects into a map using java reflection. Why is it giving error "method 'put(String,
Put objects into a map using java reflection. Why is it giving error "method 'put(String,

Time:12-02

Using javafxcollections, FXMLloader. I want to invoke put(String,Person) using reflection. After we're done with that, it'd be a plus to explore further why that error is there. My (semi pseudo)code:

* MethodInvoker.invokeIt(FXMLLoader.getnamespace(), "put", "personname", personObject, String.class, person2.getclasss()) *

The 2 class at the end are used in

(Map)Loader.getNamespace().get class().getDeclaredMethod("put", String.class, person2.getclass)

That up there, is what's giving the method not found exception.

Pointers: Fxcollections has a wrapper that makes observable map around the map used by the FXMLloader.

TIP: Had another problem almost similar but about constructor lacking in ObservableArraylist. (So reflection on getclass().get constructor().newInstance() wouldn't work because no constructor. Solved that by wrapping it in my wrapper which has constructor, takes empty ObservableArraylist as param, and some input and fills it, then I used that in the reflection API.

Something similar is the issue here and for the life of all kinds of Pies, my brain just won't accept a hacky quickfix, so I agree to get stuck on that.

CodePudding user response:

Interface Map uses generics for key and value:

Interface Map<K,V>

For your example

Interface Map<String,Person2>

These generic classes are checked by the compiler.

During runtime all generic classes are changed to Object. This process is called type erasure.

Therefore the method V put(K key, V value) or Person2 put(String key, Person2 value) changes to Object put(Object key, Object value).

You have to call

(Map)Loader.getNamespace().get class().getDeclaredMethod("put", Object.class, Object.class)
  • Related