---
title: "Java Reflection"
author: "bearjava"
date: "2008-12-07T14:10:33Z"
tags: []
slug: "java-reflection"
draft: false
lastmod: "2008-12-07T14:10:33Z"
id: 288412
url: "https://bearjava20071220091900.iteye.com/blog/288412"
---

```java

public class Customer implements Serializable{
	
	private static final long serialVersionUID = 1L;

	private long id;

	private String name = "Mike";

	private int age = 20;
	
	/**私有构造器也能通过反射访问*/
	private Customer(){
		
	}
	
	public Customer(String name,int age){
		this.name = name;
		this.age = age;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + (int) (id ^ (id >>> 32));
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final Customer other = (Customer) obj;
		if (age != other.age)
			return false;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	public String toString(){
		return this.name+": "+this.age;
	}
	
	protected void finalize(){
		System.out.println(name + " is collected.");
	}
}


```


```java

public class ReflectDemo {

	public static void main(String[] args) {
		Class<?> myclass;
		try {
			myclass = Class.forName("demo.reflect.Customer");
			useClass(myclass);
			useConstructors(myclass);
			getFields(myclass);
			getMethods(myclass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**使用Class创建对象*/
	static void useClass(Class<?> myclass) {
		try {			
			Customer customer = (Customer) myclass.newInstance();			
			customer.setName("xiong");
			customer.setAge(24);
			System.out.println(customer);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			System.out.println("----Class's newInstance method can not access private Constructor.----");
		}
	}

	/**使用Constructor创建对象*/
	static void useConstructors(Class<?> myclass) {
		Constructor<?>[] cons = myclass.getDeclaredConstructors();
		for (Constructor<?> con : cons) {
			/**动态设置构造器的访问权限，此时可以访问private的构造器*/
			con.setAccessible(true);
			try {
				if (con.getParameterTypes().length == 0) {					
					Customer customer1 = (Customer) con
							.newInstance(new Object[] {});
					System.out.println(customer1);
				}
				if (con.getParameterTypes().length == 2) {
					Customer customer2 = (Customer) con
							.newInstance(new Object[] { new String("xiong"),
									new Integer(24) });
					System.out.println(customer2);
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		}
	}

	/**动态更新对象的属性值*/
	static void getFields(Class<?> myclass) {
		Customer customer = new Customer("Haha",40);
		Field[] fields = myclass.getDeclaredFields();
		for(Field field:fields){
			if(field.getName().equals("age")){
				try {
					/**动态设置属性的访问权限，此时可以访问private的属性*/
					field.setAccessible(true);
					field.set(customer, 14);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}			
		}
		System.out.println(customer);
	}
	
	/**获取该类的所有方法*/
	static void getMethods(Class<?> myclass){
		Method[] methods = myclass.getDeclaredMethods();
		for(Method method:methods){
			System.out.println(method);
		}
	}
}


```