Java 反射概念 - 基础学习(reflect)

/**   
*create date: 2016年2月19日下午3:18:33
*update date: 2016年2月19日下午3:18:33 
*/

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author liuwb
 */
public class ReflectTrip {

	public static void main(String[] args) {
		// 1.学习如何获取 Class对象
		ReflectTrip.getClassForReflect();

		// 2.学习reflect类库(Field,Method,Constructor,Array)
		ReflectTrip.learnReflectClass();
	}

	/**
	 * 1.获取Class对象的三种方式
	 * 
	 * @author liuwb
	 * @since JDK 1.8
	 */
	public static void getClassForReflect() {
		Class<?> cls = null;
		try {
			// 1.经过Class类获取class对象;
			cls = Apple.class;

			// 2.经过Class实例获取class对象;
			cls = new Apple(null, null).getClass();

			// 3.经过Class类名称获取class对象;
			cls = Class.forName("cn.com.aben.reflect.main.Apple");

		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		System.out.print(String.valueOf(1) + ".class对象为:\t");
		System.out.println(cls != null ? cls.getName() : "null");
	}

	public static void learnReflectClass() {
		Apple ap = null;
		// 一.经过反射实例化对象的两种方式
		try {
			// ap = Apple.class.newInstance(); //一般用于无参实例化
			ap = Apple.class.getConstructor(new Class<?>[] { String.class, String.class })
					.newInstance(new Object[] { "", "" });
		} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
				| NoSuchMethodException | SecurityException e) {
			e.printStackTrace();
		}

		Method[] methods = null;
		Method method = null;
		// 二.经过反射获取并调用class对象的方法
		try {
			// 1.获取class对象的所有方法(含超类,不含私有)
			methods = Apple.class.getMethods();
			for(Method data : methods) {
				System.out.println("二.1.\t" + data.getName() + "\t" + data.getModifiers() + "\t" + data.getReturnType());
			}

			// 2.获取class对象的声明方法(含私有,不含超类)
			methods = Apple.class.getDeclaredMethods();
			for(Method data : methods) {
				System.out.println("二.2.\t" + data.getName() + "\t" + data.getModifiers() + "\t" + data.getReturnType());
			}
			
			// 3.获取class对象指定名称的方法(含超类,不含私有)
			method = Apple.class.getMethod("setName", String.class);

			// 4.获取class对象指定名称的方法(含私有,不含超类)
			method = Apple.class.getDeclaredMethod("setName", String.class);

			// 5.经过反射调用方法
			method.invoke(ap, "I'm reflect invoke method excuting.");

			method = Apple.class.getDeclaredMethod("getName");
			System.out.println(String.valueOf(2) + "." + method.invoke(ap));
		} catch (Exception e) {
			e.printStackTrace();
		}

		Field[] fields = null;
		Field field = null;
		// 三.经过反射获取并调用class对象的属性
		try {
			// 1.获取class对象的所有属性(含超类,不含私有)
			fields = Apple.class.getFields();
			for(Field data : fields) {
				System.out.println("三.1.\t" + data.getName() + "\t" + data.getModifiers());
			}

			// 2.获取class对象的声明属性(含私有,不含超类)
			fields = Apple.class.getDeclaredFields();
			for(Field data : fields) {
				System.out.println("三.2.\t" + data.getName() + "\t" + data.getModifiers());
			}

			// 3.获取class对象指定名称的属性(含超类,不含私有)
			field = Apple.class.getField("name");

			// 4.获取class对象指定名称的声明属性(含私有,不含超类)
			field = Apple.class.getDeclaredField("name");
			
			// 5.经过反射设置属性值(私有属性不能设置)
			//	field.setAccessible(true); //经过setAccessible方法使私有属性可操做(缺点:破坏对象的封装性)
			field.set(ap, "I'm field reflect.");
			
			// 6.经过反射获取属性值
			Object name = field.get(ap);
			
			System.out.println(String.valueOf(3) + "." + name);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 四.经过反射操做数组(Array)
		try {
			int length = 10;
			
			// 1.建立对应class对象的数组
			Object array = Array.newInstance(Class.forName("java.lang.String"), length);
			
			// 2.对数组进行赋值
			Array.set(array, length - 1, "nine");
			
			// 3.获取数组的指定下标元素
			String result = (String)Array.get(array, length - 1);
			
			System.out.println(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

class Apple {
	public String name;

	private String beathday;

	/**
	 * Creates a new instance of Apple.
	 *
	 * @param name
	 * @param beathday
	 */
	public Apple(String name, String beathday) {
		super();
		this.name = name;
		this.beathday = beathday;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name
	 *            the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the beathday
	 */
	public String getBeathday() {
		return beathday;
	}

	/**
	 * @param beathday
	 *            the beathday to set
	 */
	public void setBeathday(String beathday) {
		this.beathday = beathday;
	}
}
相关文章
相关标签/搜索