'Get Field Type as Interface

I'm trying to get a Map (Interface) from a Field. The Field looks like that:

private final Map<String, Object> test1 = new HashMap<>();

For that I'm trying to get the Value of it with

Map<?, ?> map = (Map<?, ?>) field.get(field.getType().newInstance());

But the Problem is, that the type is an Interface and so I can't get a new Instance. How can I now get the value of the field when the type is an Interface?

And additional to that, how can I cast it always to the right Type? So If the Map field looks like private final HashMap<String, Object> test1 = new HashMap<>(); the Type is HashMap, private final AbstractMap<String, Object> messages; type is AbstractMap, ...



Solution 1:[1]

Map map = (Map) field.get(field.getType().newInstance());

This would be incorrect even if the type wasn't an interface. Instead, if the field is in a class named MyClass, you should pass some instance of MyClass to field.get, for the object you actually want to get the field from. If you don't care which object, then the field should be static anyway, and you should pass null to field.get.

And additional to that, how can I cast it always to the right Type?

You can't cast it always to the right type, and you shouldn't bother. The Map interface is all you actually care about.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Louis Wasserman