Java - 基礎增強 - 增強for - 可變參數 - 枚舉 - 反射 - 內省 - 泛型

增強for:注意:只適合取數據

// 使用增強for遍歷Map集合
	@Test
	public void test1() {
		
		LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
		
		map.put("張三", 20);
		map.put("李四", 21);
		map.put("王五", 22);
		map.put("趙六", 23);
		
		for (Map.Entry<String, Integer> me : map.entrySet()) {
			System.out.println(me.getKey() + me.getValue());
		}
	}

	// 使用傳統for遍歷Map集合
	@Test
	public void test2() {

		LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();

		map.put("張三", 20);
		map.put("李四", 21);
		map.put("王五", 22);
		map.put("趙六", 23);

		Set<String> keySet = map.keySet();

		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String key = it.next();
			int value = map.get(key);
			System.out.println(key + value);
		}
	}

可變參數:注意:可變參數必須位於最後一項。

public class Demo1 {
	/*
	 * 可變參數:適用於參數個數不確定,java把可變參數當做數組處理。
	 * 
	 * 注意:如果出現可變參數的重載的情況,則編譯器會自動調用最合適的方法匹配。
	 * 
	 * 但是:
	 * public class Demo2 {
	       static void f(float i,Character...args){
	              System.out.println("first");
	       }
 
	       static void f(Character...args){
	              System.out.println("second");
	       }
      
	       public static void main(String[] args){
	              f(1,'a');
	              f('a','b');//Error無法確定調用哪個方法
	       }
		}
	 * 
	 */
	public static void main(String[] args) {
		int[] i = { 1, 2, 3 };
		String[] s = { "a", "b", "c" };

		show(i);	 // 編譯器會自動的把參數轉變爲數組的 show(new Object[]{i})
		show(s); 	//  當使用數組作爲參數(類型兼容),那麼編譯器就不會幫你轉化爲數組了
		show(s, i);//   show(new Object[]{s,i})
	}

	/***********
	 * jdk5以後
	 ***********/
	private static void show(Object... obj) {
		System.out.println("數組長度:" + obj.length);
	}

	/***********
	 * jdk5以前
	 ***********/
	private static void show2(Object[] obj) {
		System.out.println(obj.length);
	}
}

輸出結果:

數組長度:1
數組長度:3
數組長度:2

枚舉(enumeration)類:單例、多例、用於限定範圍、是一個特殊類、繼承Enum、每一個枚舉值代表一個實例對象

public class EnumTest {
	/*
	 * 編寫一個星期幾的枚舉WeekDay, 
	 * 要求:枚舉值MON,TUE,WED,THU,FRI,SAT,SUN 
	 * 調用方法返回中文格式的星期。
	 */
	public static void main(String[] args) {
		printDay(WeekDay.WED);
	}

	private static void printDay(WeekDay day) {
		System.out.println(day.getEnday() + ":" + day.getCnday());
	}
}

enum WeekDay {
	/*
	 * 枚舉是用來限定範圍,枚舉值就是它的具體取值範圍
	 * 當有多個枚舉值的時候,可以通過構造函數的重載,來表示不同的對象。
	 * 在這裏枚舉只是用來封裝星期信息,每一個枚舉值代表一個星期對象。
	 * 每一個星期對象應該有一個英文的星期成員,和一個把英文星期轉換成中文的方法。
	 */
	MON("Monday") {
		public String getCnday() {
			return "星期一";
		}
	},
	TUE("Tuesday") {
		public String getCnday() {
			return "星期二";
		}
	},
	WED("Wednesday") {
		public String getCnday() {
			return "星期三";
		}
	},
	THU("Thursday") {
		public String getCnday() {
			return "星期四";
		}
	},
	FRI("Friday") {
		public String getCnday() {
			return "星期五";
		}
	},
	SAT("Saturday") {
		public String getCnday() {
			return "星期六";
		}
	},
	SUN("Sunday") {
		public String getCnday() {
			return "星期天";
		}
	};

	private String enday;

	public String getEnday() {
		return enday;
	}	

	WeekDay(String day) {
		enday = day;
	}
	public abstract String getCnday();
}

反射:1.加載類字節碼Class  2.解剖出類的個個組成部分  3.使用........主要用於框架...

public class Reflex {

	// 反射無參數的構造函數
	@Test
	public void test1() throws Exception {

		Class clazz = Class.forName("cn.itcast.demo.Person");
		Constructor c = clazz.getConstructor(null);
		Person p = (Person) c.newInstance(null);
	}

	// 反射有參數的構造函數
	@Test
	public void test2() throws Exception {

		Class clazz = Class.forName("cn.itcast.demo.Person");
		Constructor c = clazz.getConstructor(String.class);
		Person p = (Person) c.newInstance("張三");
	}

	// 反射主函數
	@Test
	public void test3() throws Exception {

		Class clazz = Class.forName("cn.itcast.demo.Person");
		Method m = clazz.getMethod("main", String[].class);
		/*
		 * 主函數的參數是一個字符串數組...
		 * invoke(Object obj, Object... args)方法...
		 * 接收的參數是一個可變參數列表。如果直接傳遞一個字符串對象數組,編譯器不會幫你把數組封裝到Object數組中
		 * 那麼invoke()方法內部在遍歷這個數組獲取參數的時候,遍歷到的結果是空
		 * 所以只能把他提升爲Object對象,這樣它纔會被編譯器當成一個元素封裝到Object數組中
		 * 
		 */
		m.invoke(null, (Object) new String[] {});
	}

	// 反射私有方法
	@Test
	public void test4() throws Exception {

		Class clazz = Class.forName("cn.itcast.demo.Person");
		Method m = clazz.getDeclaredMethod("getName", null);
		// 修改訪問權限,強制訪問、、、
		m.setAccessible(true);
		String str = (String) m.invoke(clazz.newInstance(), null);
		System.out.println(str);
	}
	
	// 反射字段
	@Test
	public void test5() throws Exception {

		Class clazz = Class.forName("cn.itcast.demo.Person");
		Person p = (Person) clazz.newInstance();
		Field numField = clazz.getDeclaredField("num");
		// 修改訪問權限,強制訪問、、、
		numField.setAccessible(true);
		int num = numField.getInt(p);
		System.out.println(num);

		Field numsField = clazz.getDeclaredField("nums");
		Integer[] nums = (Integer[]) numsField.get(p);
		System.out.println(nums);
	}
}


內省:通過反射機制獲取 setter和 getter

1.使用SUN的 java.beans:

public class JavaBeanTest {
	@Test
	public void test1() throws Exception {

		BeanInfo bi = Introspector.getBeanInfo(cn.itcast.bean.User.class);
		PropertyDescriptor[] pds = bi.getPropertyDescriptors();
		for (PropertyDescriptor pd : pds) {
			System.out.println(pd.getName());
		}
	}

	@Test
	public void test2() throws Exception {
		
		Class clazz = Class.forName("cn.itcast.bean.User");
		User u = (User) clazz.newInstance();
		PropertyDescriptor pd = new PropertyDescriptor("name", cn.itcast.bean.User.class);
		
		
		Method setMethod = pd.getWriteMethod();
		setMethod.invoke(u, "張三");
		
		Method getMethod = pd.getReadMethod();
		String name = (String) getMethod.invoke(u, null);
		System.out.println(name);
	}
}

2.使用beanutils:

public class BeanUtilTest {

	// 使用 BeanUtils
	@Test
	public void test1() throws Exception {

		User u = (User) Class.forName("cn.itcast.bean.User").newInstance();

		BeanUtils.setProperty(u, "name", "張三");

		String name = BeanUtils.getProperty(u, "name");

		System.out.println(name);
	}

	// 自定義日期轉換器 ConvertUtils
	@Test
	public void test2() throws Exception {

		String name = "張三";
		String birthday = "1949-10-1";
		
		ConvertUtils.register(new Converter() {

			public <T> T convert(Class<T> type, Object value) {

				if (value == null)
					return null;
				if (!(value instanceof String))
					throw new ConversionException("不能轉換");

				String str = (String) value;

				if (str.equals(""))
					return null;

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				try {
					return  (T) df.parse(str);
				} catch (ParseException e) {
					throw new RuntimeException(e);
				}
			}
		}, Date.class);

		User u = new User();
		BeanUtils.setProperty(u, "name", name);
		BeanUtils.setProperty(u, "birthday", birthday);

		System.out.println(BeanUtils.getProperty(u, "birthday"));
		System.out.println(BeanUtils.getProperty(u, "name"));
	}
}

泛型(generic):注意:如果兩邊都使用泛型,兩邊必須都一樣、、、類型參數變量、、、實際類型參數、、、

public class GenericTest {
	/*
	 * 編寫一個泛型方法,接收任意數組,並顛倒順序
	 */
	public static void main(String[] args) {

		Integer[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		changeArr(arr);
		for (int val : arr) {
			System.out.println(val);
		}
	}

	public static <T> void changeArr(T[] arr) {

		int len = arr.length;

		if (len == 0) return;

		int centre = len / 2;
		int end = len - 1;

		for (int star = 0; star < centre; star++, end--) {

			T temp = arr[star];
			arr[star] = arr[end];
			arr[end] = temp;
		}
	}
}
























發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章