java实现任意对象数组扩展(代码复用)

public class Main{
	public static void main(String[] args){	
		Person[] person=new Person[]{
			new Person(1024,"wawa");
			new Person(1023,"xiaoming");
			new Person(1000,"lihong");
		}
		int the_num_of_you_want=5;
		Object t=copy(person,the_num_of_you_want);
		Person[] p2=(Person[])t;
		for(Person e:p2){
			if(e!=null)
			System.out.println(e.getName());
		}
		
	}
	public static Object copy(Object a,int newlength){
		Class c1=a.getClass();
		if(!isArray(c1))return null;
		Class c2=c1.getComponentType();
		int length=Array.getLength(a);
		Object temp=Array.newInstance(c2,newlength);
		System.arraycopy(a,0,temp,0,Math.min(newlength,));
		return temp;
	}

}

class Person{
	private int id;
	private String name;
	public Person(){}
	public Person(int id,String name){
		this.id=id;
		this.name=name;
	}


}

实现任意对象数组的扩展,首先传入对象a,先判断a所属的类,如果a所属的类不是Array,则直接返回null。用getComponentType()得到数组对应的类型,这个方法在Class类里,然后用Array的静态方法newInstance()创建一个数组,再用arraycopy()拷贝数组里每个对象,最后返回新的数组对象temp。

你可能感兴趣的:(java实现任意对象数组扩展(代码复用))