Java- by reflection across the generic inspection

First, the requirement description

Existing an ArrayList array= new ArrayList (); How to add the type of data in the array of String? ? ?

Second, think

We know that once in the collection classes specified generic type, only the type used in the collection. But we can use reflection to inspect the generic crossed. For example, using the reflection in the acquisition add ArrayList () method, then call when the add method, it will cross the generic inspection. Decompile we can see this phenomenon.

Following existing code that uses the generic when creating ArrayList.

public class Test {
	public static void main(String[] args) throws Exception {
		ArrayList<Integer> array = new ArrayList<Integer>();
	}
}

Decompile view the file using the Class, you will find no increase in generics during this time create ArrayList.

This is because generic checks are carried out at compile time, which means that the compiled add () method, and in fact did not specify generic add () method is the same, are no generic examination.

Therefore, by reflecting the acquired ArrayList Class object file add () method when the calling add () method is not a generic inspection.

Third, to achieve demand

Now we use reflection to implement this requirement.

code show as below:

public class Test {
	public static void main(String[] args) throws Exception {
		ArrayList<Integer> array = new ArrayList<Integer>();
		array.add(18);

		Class c = array.getClass();
		Method m = c.getDeclaredMethod("add", Object.class);
		m.invoke(array, "Hello");
		System.out.println(array);
	}
}

Test results are as follows:

Guess you like

Origin www.cnblogs.com/Java-biao/p/12590897.html