通过反射打印Set

java.util.HashSet 10 20 30 10 20 60 ...    or

java.util.TreeSet 10 20 30 10 20 60 ...

Please write a program with java reflection function to put all the numbers into a set, and then print the set.


package test;

import java.lang.reflect.Array;
import java.util.HashSet;
import java.util.TreeSet;

public class SetReflection {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		int[] num = new int[] { 10, 20, 30, 10, 20, 60 };
		HashSet<Integer> hashSet = new HashSet<Integer>();
		TreeSet<Integer> treeSet = new TreeSet<Integer>();
		for (int i = 0; i < num.length; i++) {
			hashSet.add(num[i]);
			treeSet.add(num[i]);
		}
		printObject(hashSet);
		printObject(treeSet);
	 
	}
	private static  void printObject(Object obj) throws InstantiationException, IllegalAccessException{
		  Class clazz = obj.getClass();
		  if(clazz.isArray()) {//判断数组
		   int len = Array.getLength(obj);//得到数组的长度
		   for (int i = 0; i < len; i++) {
		    System.out.print(Array.get(obj, i));
		   }
		   System.out.println();
		   for(int i = 0; i < len; i++){
		    Array.set(obj, i, 99);//赋值
		    System.out.print(Array.get(obj, i));
		   }
		  }else {
		   System.out.println();
		   System.out.println(obj);
		   
		  }
		 }
		
}


结果:

 

[20, 10, 60,30]

 

[10, 20, 30,60]

 



你可能感兴趣的:(通过反射打印Set)