Do you really understand generics when people around you are typing the wrong type
Today, when I talk about reflection with my colleagues, I throw a question ~
When we use collection classes, we usually place type constraints on this object, do a compiler check on it, and raise an error if it is passed a different type, as shown below
ArrayList<Integer> arrayList =new ArrayList<Integer>();
arrayList.add("111");
Copy the code
So if you use reflection, can you bypass his type checking ???? Can you successfully call??
That’s today’s question if it’s ok and answer why!!
Let’s look at the code test
// Create a list ArrayList<Integer> ArrayList =new ArrayList<Integer>(); Method add = arrayList.getClass().getDeclaredMethod("add", integer.class); // Invoke his add method add.invoke(arrayList,111); System.out.println(arrayList);Copy the code
The test result is: error !!!!! In other words, for generic types, the Method Method can only get the base class when using reflection, so there is no type constraint when using reflection. Instead, use the Object whose reflection must get the base class as the parameter. This is a false statement. You can’t do type constraints at all with reflection !!!!
Bang, bang, bang on the blackboard
So, when we use reflection to call generic methods, it’s important to pay attention to the type we roll in. Be sure to follow Java’s type erasure rules and find the base type as follows
- All parameterized container classes are erased to non-parameterized (raw type); For example, List, List
-
are erased to List;
- All parameterized arrays are erased to nonparameterized arrays; For example, List[], erased to List[];
- The Raw type container class is erased into itself, as in List.
- Native types (int,String, and wrapper classes) are erased into themselves;
- The argument type E is erased to Object;
- All constraint parameters such as
and are erased to E; - If there are more than one constraint, the first one is erased. For example,
is erased to Object.