jeudi 9 juin 2022

How to make a Map object from Field(reflect) with all values?

I have a field annotated with the MaskedMap annotation and it is a Map class. Then I get this field through the annotation search and I want to get all the values of this field that are in the Map. And I can't make from field to Map

private void putMapParamsMasks(Class<?> type) {
                    for (Field field : type.getDeclaredFields()) {
                        MaskedMap maskedMap = field.getAnnotation(MaskedMap.class);
                        if (maskedMap != null) {
                            for (int i = 0; i < maskedMap.keys().length; i++) {
                                try {
                                    Map<String, String> map = (Map<String, String>) field.get(new HashMap<String,String>()); //failed
                                    valueMasks.put(map.get(maskedMap.keys()[i]), maskedMap.masks()[i].newInstance());
                                } catch (InstantiationException | IllegalAccessException e) {
                                    throw new UnexpectedException(e);
                                }
                            }
                        }
                    }
                }

I tried to do it like this:

Map<String, String> map =(Map<String, String>) field.get(type);

But I caught it

java.lang.IllegalArgumentException: Can not set java.util.Map field com.ConfirmRequest.params to null value




Aucun commentaire:

Enregistrer un commentaire