_072_反射之内省、复制对象

==============

普通对象的字段复制

// 下面是普通的对象的字段复制;
		Person person1 = new Person(); // 老对象
		person1.setName("荒天帝");
		Person target = new Person(); // 新的对象

		//拿到类描述符
		Class<Person> clazz = Person.class;
		
		// 获取全部字段描述
		Field[] field1 = clazz.getDeclaredFields();
		
		//全部设置可访问
		for (Field f : field1)
		{
			if (!f.isAccessible()) // 是否可访问
			{
				f.setAccessible(true);
			}

			// 把老对象的数值一个一个get出来,然后一个一个设置到新对象里
			Object fvalue = f.get(person1);
			f.set(target, fvalue); 
		}

		 System.out.println("test:"+target.getName());

递归遍历类的所有属性,包括继承的

public class Test2
{
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException,
			SecurityException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException
	{
		Class clazz = Dog.class;
		print_field(clazz);
	}

	// 递归遍历 带继承的对象的字段
	public static void print_field(Class clazz)
	{
		if (clazz.equals(Object.class))// 如果已经到了最基类了,就return
		{
			return;
		}
		Field[] fields1 = clazz.getDeclaredFields();// 能获取本类所有的字段,private也可以,但是只能是本类的
		for (Field f : fields1) // 不能用getFields因为它本类的private不算,只算继承来的public
		{
			String fname = f.getName();
			System.out.println(fname);
		}

		clazz = clazz.getSuperclass();// 取得父类的类描述符
		print_field(clazz);
	}
}

class Animal
{
	private int id;

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}
}

class Dog extends Animal
{
	public String name;

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

}

Introspector(内省)获取字段

class Test1
{
	public static void main(String[] args)
			throws IllegalArgumentException, IllegalAccessException, IntrospectionException
	{
		Introspective();
	}

	// 下面是内省获取字段
	public static void Introspective() throws IntrospectionException
	{
		BeanInfo beanInfo1 = Introspector.getBeanInfo(Dog.class);// 获取Bean信息,需要传入类描述符
		PropertyDescriptor[] pds1 = beanInfo1.getPropertyDescriptors();// PropertyDescriptor(属性描述)
		for (PropertyDescriptor p : pds1)
		{
			System.out.println(p.getName()); // 内省获取属性描述的方式是根据get和set方法,只有get和set达到固定的格式
												// 比如getName()
												// 就可以知道get后面是name,且get有返回值无参数,set相反
			Method m = p.getReadMethod();// 还可以获取get方法
		}
	}

}

class Animal
{
	private int id;

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}
}

class Dog extends Animal
{
	public String name;

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
}

猜你喜欢

转载自blog.csdn.net/yzj17025693/article/details/82813419
今日推荐