一:Java 概述java
1、簡介程序員
1. 定義:Java 是一門面向對象編程語言,不只吸取了C++語言的各類優勢,還摒棄了C++裏難以理解的多繼承、指針等概念,所以Java語言具備功能強大和簡單易用兩個特徵。Java語言做爲靜態面向對象編程語言的表明,極好地實現了面向對象理論,容許程序員以優雅的思惟方式進行復雜的編程。應用在桌面應用程序、Web應用程序、分佈式系統和嵌入式系統等領域。正則表達式
2. 發展歷程數據庫
1. 1996年1月,Sun公司發佈了Java的第一個開發工具包(JDK 1.0),這是Java發展歷程中的重要里程碑,標誌着Java成爲一種獨立的開發工具。編程
2. 1999年6月,Sun公司發佈了第二代Java平臺(簡稱爲Java2)的3個版本:J2ME(Java2 Micro Edition,Java2平臺的微型版),應用於移動、無線及有限資源的環境;J2SE(Java 2 Standard Edition,Java 2平臺的標準版),應用於桌面環境;J2EE(Java 2Enterprise Edition,Java 2平臺的企業版),應用於基於Java的應用服務器。Java 2平臺的發佈,是Java發展過程當中最重要的一個里程碑,標誌着Java的應用開始普及。小程序
3. 2005年6月,在Java One大會上,Sun公司發佈了Java SE 6。此時,Java的各類版本已經改名,已取消其中的數字2,如J2EE改名爲JavaEE,J2SE改名爲JavaSE,J2ME改名爲JavaME。數組
4. 2007年3月起,全世界全部的開發人員都可對Java源代碼進行修改。安全
5. 2009年,甲骨文公司宣佈收購Sun。2014年,甲骨文公司發佈了Java8正式版服務器
2、編程開發網絡
1. 開發環境
1. JDK(Java Development Kit)稱爲Java開發包或Java開發工具,是一個編寫Java的Applet小程序和應用程序的程序開發環境。JDK是整個Java的核心,包括了Java運行環境(Java Runtime Environment),一些Java工具和Java的核心類庫(Java API)。不論什麼Java應用服務器實質都是內置了某個版本的JDK。主流的JDK是Sun公司發佈的JDK,除了Sun以外,還有不少公司和組織都開發了本身的JDK,例如,IBM公司開發的JDK,BEA公司的Jrocket,還有GNU組織開發的JDK [13] 。
2. JRE(JAVA Runtime Environment)是JavaSE API子集和Java虛擬機這兩部分的統稱,是支持Java程序運行標準環境。JDK默認集成JRE,可是運行普通Java程序只需安裝JRE。
2. 開發工具
1. Eclipse:一個開放源代碼的、基於Java的可擴展開發平臺。
2. NetBeans:開放源碼的Java集成開發環境,適用於各類客戶機和Web應用。
3. IntelliJ IDEA:在代碼自動提示、代碼分析等方面的具備很好的功能。
4. MyEclipse:由Genuitec公司開發的一款商業化軟件,是應用比較普遍的Java應用程序集成開發環境
3、特色
1. 簡單性:Java 摒棄了C++的操做符過載、多繼承特徵、結構和指針,可以自動處理對象的引用和間接引用。
2. 面向對象:Java 是一個面向對象的語言。類(class)是數據和操做數據的方法的集合,數據(data)和方法(method)一塊兒描述對象(object)的狀態和行爲。除此以外Java還可使用各類程序包(Package)。
3. 分佈性:Java 程序編譯一次便可處處運行。Java既支持各類層次的網絡鏈接,又以Socket類支持可靠的流(stream)網絡鏈接,因此用戶能夠產生分佈式的客戶機和服務器。
4. 編譯和解釋性:Java 編譯程序最終生成字節碼(byte-code)文件,而不是一般的機器碼,能夠在任何實現了Java解釋程序和運行系統(run-time system)的系統上運行。
5. 穩健性:Java是一個強類型語言,它容許擴展編譯時檢查潛在類型不匹配問題的功能。Java要求顯式的方法聲明,它不支持C風格的隱式聲明。這些嚴格的要求保證編譯程序能捕捉調用錯誤,這就致使更可靠的程序。
6. 安全性:Java的存儲分配模型是它防護惡意代碼的主要方法之一。Java沒有指針,因此程序員不能獲得隱蔽起來的內幕和僞造指針去指向存儲器。更重要的是,Java編譯程序不處理存儲安排決策,因此程序員不能經過查看聲明去猜想類的實際存儲安排。編譯的Java代碼中的存儲引用在運行時由Java解釋程序決定實際存儲地址。Java運行系統使用字節碼驗證過程來保證裝載到網絡上的代碼不違背任何Java語言限制。
7. 可移植性:Java 使得語言聲明不依賴於實現的方面,Java 環境自己對新的硬件平臺和操做系統是可移植的。
8. 高性能:Java 字節碼格式設計時考慮到這些「及時」編譯程序的須要,因此生成機器代碼的過程至關簡單,它能產生至關好的代碼。
9. 多線程:Java 是多線程語言,它提供支持多線程的執行(也稱爲輕便過程),能處理不一樣任務,使具備線索的程序設計很容易。Java的lang包提供一個Thread類,它支持開始線索、運行線索、中止線索和檢查線索狀態的方法。
10. 動態性:Java 語言設計成適應於變化的環境,它是一個動態的語言。例如,Java中的類是根據須要載入的,甚至有些是經過網絡獲取的。
4、學習路線
二:Java 基礎知識
1、標識符和關鍵字
1. 標識符
1. 在java語言中,用來標誌類名、對象名、變量名、方法名、類型名、數組名、包名的有效字符序列,稱爲「標識符」;
2. 標識符由字母、數字、下劃線、美圓符號組成,且第一個字符不能是數字;
3. java語言區分大小寫;
4. 標誌符命名規則:類名首字母大寫,變量名和方法名採用駝峯標誌法,包名全小寫,常量全大寫,多個單詞之間用「_」隔開;
2. 關鍵字
1. 在java語言中,有一些專門的詞彙已經被賦予了特殊的含義,不能再使用這些詞彙來命名標識符,這些專有詞彙,稱爲「關鍵字」;
2. java有50個關鍵字和3個保留字,均不能用來命名標識符;
3. true、false、null不是關鍵字,是保留字,可是仍不能用來命名標識符;
2、數據類型
1. 分類
2. 存儲原理
1. 基本類型的存儲原理:直接存儲在內存中的內存棧上的,數據自己的值就是存儲在棧空間裏面,而Java語言裏面八種數據類型是這種存儲模型;
2. 引用類型的存儲原理:按照存儲對象的內存模型來進行數據存儲的,「引用」是存儲在有序的內存棧上的,而對象自己的值存儲在內存堆上的;
3、運算符
4、流程控制語句
1. 條件分支語句
1 package pers.mj;
2
3 import org.junit.Test;
4
5 public class Demo {
6 @Test
7 public void test() {
8 int a = 10;
9 int b = 5;
10
11 // if 條件判斷
12 if (a > 8) { // 條件
13 System.out.println(a + "大於8");
14 if (a < 12) {
15 System.out.println(a + "小於12");
16 }
17 } else {
18 System.out.println(a + "小於8");
19 }
20
21 // switch 條件判斷
22 // switch 語句中的變量類型能夠是: byte、short、int 或者 char。
23 // 從 Java SE 7 開始,switch支持字符串 String 類型了,同時 case 標籤必須爲字符串常量或字面量。
24 char job = 'C';
25 switch (job) {
26 case 'A':
27 System.out.println("優秀");
28 break;
29 case 'B':
30 System.out.println("良好");
31 break;
32 case 'C':
33 System.out.println("及格");
34 break;
35 default:
36 System.out.println("不及格");
37 break;
38 }
39 }
40 }
1 package pers.mj;
2
3 import static org.hamcrest.CoreMatchers.instanceOf;
4
5 import org.junit.Test;
6
7 public class Demo {
8 @Test
9 public void test() {
10 int sum = 0;
11 int i = 0;
12 // while 循環:迭代條件明確的數據
13 while (i <= 100) {
14 sum+=i;
15 i++;
16 }
17 System.out.println(sum);
18
19 // for 循環:迭代條件明確的數據
20 for (int j = 0; j <= 100; j++) {
21 sum += j;
22 }
23 System.out.println(sum);
24
25 // foreach 循環:用來迭代引用類型數據
26 int [] array = {0,1,2,3,4,5,6};
27 for (int j : array) {
28 System.err.println(j);
29 }
30 }
31 }
三:數組
1、概述
1. 數組的概念:相同數據類型元素的集合
2. 數組的做用:用來存儲基本數據類型和引用數據類型的數據
2、經常使用操做
數據經常使用操做
3、Arrays工具類
Arrays工具類經常使用操做
四:面向對象
1、簡介
1. 概念:面向對象也即OOP(Object Oriented Programming),是一種編程思想,它以對象做爲基本的單元來構建系統,具備三大特徵和五大原則。
2. 三大特徵:
1. 封裝:隱藏對象的屬性和實現細節,僅對外提供公共訪問方式,提升安全性。
2. 繼承:提升代碼複用性,是實現多態的前提。
3. 多態:父類或接口定義的引用變量指向子類或具體實現類的實例對象,提升了代碼的拓展性。
3. 五大原則
1. 單一職責原則SRP(Single Responsibility Principle):類的功能要單一。
2. 開放封閉原則OCP(Open-Close Principle):擴展開放,修改關閉。
3. 裏式替換原則LSP(the Liskov Substitution Principle LSP):子類能夠替換父類出如今父類可以出現的任何地方。
4. 依賴倒置原則DIP(the Dependency Inversion Principle DIP):高層次的模塊不該該依賴於低層次的模塊,他們都應該依賴於抽象。抽象不該該依賴於具體實現,具體實現應該依賴於抽象。
5. 接口分離原則ISP(the Interface Segregation Principle ISP):設計時採用多個與特定客戶類有關的接口比採用一個通用的接口要好。
2、封裝
1. 核心思想:隱藏細節,保護數據安全。
2. 訪問權限
3. 封裝代碼實現
1 public class Encapsulation {
2 // 1.成員屬性私有化
3 private String name;
4 private String pwd;
5
6 // 2.提供getter和setter方法來訪問
7 public String getName() {
8 return name;
9 }
10
11 public void setName(String name) {
12 this.name = name;
13 }
14
15 public String getPwd() {
16 return pwd;
17 }
18
19 public void setPwd(String pwd) {
20 this.pwd = pwd;
21 }
22 }
23
24 class TestEncapsulation {
25 public static void main(String[] args) {
26 Encapsulation test = new Encapsulation();
27 // 3.經過setter方法設置屬性值
28 test.setName("封裝");
29 test.setPwd("666");
30 // 4.經過getter方法獲取值
31 System.out.println("姓名:" + test.getName() + " -- 密碼:" + test.getPwd());
32
33 }
34 }
3、方法的重載和重寫
1. 方法的重載:方法名相同,參數列表不一樣
2. 方法的重寫:方法名、返回值類型、參數列表都相同,構造方法和使用final、static修飾的方法不能被重寫
3. 方法重載和重寫代碼實現
1 package pers.mj;
2
3 public interface Override {
4 /**
5 * 方法的重載:方法名相同,參數列表不一樣
6 */
7 public void query(int id);
8
9 public int query(int id, String username);
10
11 }
12
13 class Test implements Override {
14 /**
15 * 方法的重寫:方法的全部東西都同樣,只有方法實體不一樣。
16 */
17 public void query(int id) {
18 System.out.println("我重寫了接口的方法");
19
20 }
21
22 public int query(int id, String username) {
23 System.out.println("我也能夠重寫父類的方法");
24 return 0;
25 }
26
27 }
4、繼承
1. 核心思想:解決代碼冗餘,提升代碼的複用性
2. 繼承關係:知足is-a的關係,父類更通用,子類更具體。
3. 繼承代碼實現
1 /**
2 * 1. 將類中重複的部分提取成爲父類
3 */
4 public class Animal {
5 private String name;
6 private String food;
7
8 public Animal(String name, String food) {
9 this.name = name;
10 this.food = food;
11 }
12
13 public void eat() {
14 System.out.println(name + "正在吃" + food);
15 }
16 }
17
18 /**
19 * 2. 子類繼承父類,對父類進行擴展
20 */
21 public class Cat extends Animal {
22
23 public Cat(String name, String food) {
24 super(name, food);
25 }
26 }
27 public class Dog extends Animal{
28
29 public Dog(String name, String food) {
30 super(name, food);
31 }
32 }
33
34 /**
35 * 3. 測試
36 */
37 public class TestExtends{
38 public static void main(String[] args) {
39 Animal cat = new Cat("三三", "魚");
40 cat.eat();
41 Animal dog = new Dog("二哈", "香腸");
42 cat.eat();
43 }
44 }
5、多態
1. 核心思想:提升代碼可維護性和可擴展性
2. 實現多態的三個必要條件:繼承、重寫、父類引用指向子類對象(向下轉型)
3. 多態的實現方式:重寫、接口、抽象類和抽象方法
4. 多態代碼實現
1 /**
2 * 1. 建立動物類,定義動物吃什麼的方法
3 */
4 class Animals {
5 private String name;
6 private String food;
7
8 public Animals(String name, String food) {
9 super();
10 this.name = name;
11 this.food = food;
12 }
13
14 public void eat() {
15 System.out.println(this.name + "會吃" + this.food);
16 }
17 }
18
20 /**
21 * 2. 建立Cat類來實現吃的功能
22 */
23 class Cat extends Animals{
24 public Cat(String name, String food) {
25 super(name, food);
26 }
27
28 @Override
29 public void eat() {
30 super.eat();
31 }
32 }
33
35 /**
36 * 3. 經過向上轉型和向下轉型實現多態
37 */
38 public class Test01 {
39 public static void main(String[] args) {
40 // 向下轉型
41 Animals animals = new Cat("三三", "魚");
42 animals.eat();
43 // 向上轉型
44 Cat cat = (Cat) animals;
45 cat.eat();
46 }
47 }
6、抽象類
1. 核心思想:讓代碼有更強的可擴展性
2. 特色
1. 抽象類不能實例化對象。
2. 若是一個類包含抽象方法,那麼該類必須是抽象類
3. 任何子類必須重寫父類的抽象方法(具體實現),或者聲明自身爲抽象類
4. 抽象類中的抽象方法只有方法聲明,沒有方法體
5. 構造方法和static修飾的方法不能聲明爲抽象方法
3. 抽象類代碼實現
1 /**
2 * 1. 建立員工抽象類
3 */
4 abstract class Employees {
5 // 成員變量
6 private String name;
7 private String address;
8 private Integer number;
9
10 // 構造方法
11 public Employees(String name, String address, Integer number) {
12 System.out.println("Employees.Employees()");
13 this.name = name;
14 this.address = address;
15 this.number = number;
16 }
17
18 // 定義信息抽象函數
19 public abstract void call();
20
21 // 省略getter 和 setter方法
22 ......
23 }
24 }
25
26 class Salary extends Employees {
27 private Double salary;
28
29 public Salary(String name, String address, Integer number, Double salary) {
30 super(name, address, number);
31 this.salary = salary;
32 System.out.println("Salary.Salary()");
33 }
34
35 // 2. 重寫父類的抽象方法
36 @Override
37 public void call() {
38 System.out.println(super.getNumber() + "是" + super.getName() + "的電話,他住在" +
39 super.getAddress() + "他如今的工資是" + this.salary);
40 }
41 }
42
43 public class Test {
44 public static void main(String[] args) {
45 // 3. 抽象類的對象必須由子類去實例化
46 Employees emp = new Salary("孫悟空", "花果山", 1234, 222.66);
47 emp.call();
48 }
49 }
7、接口
1. 核心思想:讓代碼有更強的可擴展性
2. 特色
1. 接口不能實例化對象,沒有構造方法
2. 接口中的方法只能是抽象方法,默認使用public abstract修飾
3. 接口中的變量只能是常量,默認使用public static final修飾
4. 接口支持多繼承,但接口不是被繼承了,而是被實現了
3. 接口和抽象類的區別
1. 接口中的方法只能是抽象方法,而抽象類中的方法能夠是普通方法,構造方法和抽象方法
2. 接口中的變量只能是常量,而抽象類中的方法能夠是任意類型
3. 接口中不能含有靜態代碼塊和靜態方法,而抽象類中能夠有
4. 一個類能夠實現多個接口,但一個類只能繼承一個抽象類
1 /**
2 * 1. 建立Animal接口
3 */
4 interface Animal {
5 // 定義睡覺抽象方法
6 void sleep();
7
8 // 定義吃飯抽象方法
9 void eat();
10 }
11
12 /**
13 * 2. 建立Dog接口繼承Animal接口
14 */
15 interface Dog extends Animal {
16 // 定義游泳抽象方法
17 void swim();
18 }
19
20 /**
21 * 3. 建立HaShiQi接口繼承Dog和Animal接口,實現多繼承
22 */
23 interface HaShiQi extends Dog, Animal {
24 // 定義拆家抽象方法
25 void demolishedFamily();
26 }
27
28 /**
29 * 4. 建立測試類來實現接口,而且複寫全部抽象方法
30 */
31 public class TestAnimal implements HaShiQi {
32
33 @Override
34 public void swim() {
35 System.out.println("哈士奇會游泳");
36 }
37
38 @Override
39 public void sleep() {
40 System.out.println("哈士奇會睡覺");
41 }
42
43 @Override
44 public void eat() {
45 System.out.println("哈士奇喜歡吃苦瓜");
46 }
47
48 @Override
49 public void demolishedFamily() {
50 System.out.println("哈士奇會拆家");
51 }
52
53 public static void main(String[] args) {
54 // 使用多態實例化對象
55 HaShiQi dog = new TestAnimal();
56 dog.eat();
57 dog.sleep();
58 dog.demolishedFamily();
59 dog.swim();
60 }
61 }
五:經常使用類
1、Number & Math 類:包含了數據類型轉換和用於執行基本數學運算的屬性和方法。
1. 經常使用方法
1 package pers.mj;
2
3 import java.util.Random;
5 import org.junit.Test;
6
7 public class TestMathAndNumber {
8 @Test
9 public void testMath() {
10 // 獲取絕對值
11 System.out.println(Math.abs(-10)); // 10
12 // 求平方根
13 System.out.println(Math.sqrt(4)); // 2.0
14 // 求冪
15 System.out.println(Math.pow(2, 5)); // 32.0
16 // 天然對數
17 System.out.println(Math.log(100)); // 4.6~
18 // 向上取整
19 System.out.println(Math.floor(2.80)); // 2.0
20 // 向下取整
21 System.out.println(Math.ceil(2.25)); // 3.0
22 // 四捨五入
23 System.out.println(Math.round(2.25)); // floor(2.25+0.5)=2
24 // 生成指定範圍的隨機數
25 System.out.println(randomNumber(1000, 9999));
26
27 }
28
29 public static Integer randomNumber(Integer minNum,Integer maxNum) {
30 return new Random().nextInt((maxNum - minNum + 1) + minNum);
31 }
32 }
2、String 類
1. 經常使用方法
2. 經常使用操做
1 package pers.mj;
2
3 import org.junit.Test;
4
5 public class TestString {
6 @Test // 基本操做
7 public void testBase() {
8 // 定義字符串
9 String str = " 你再惹我,我給你一個大嘴巴子 ";
10 // 獲取字符串長度
11 System.out.println(str.length());
12 // 忽略字符串兩邊的空行
13 System.out.println(str.trim());
14 // 獲取指定索引出的字符
15 System.out.println(str.charAt(3));
16 // 將字符串轉換並存儲在字符數組中
17 char[] chardst = new char[1024];
18 str.getChars(0, 7, chardst, 0);
19 System.out.println(chardst);
20
21 }
22
23 @Test // 字符串比較
24 public void testCompare() {
25 String str1 = "elapant";
26 String str2 = "ELEPANT";
27 String str3 = "Apple";
28 String str4 = "apple";
29 // compareTo()方法:不忽略大小寫
30 if (str1.compareTo(str2) > 0) {
31 System.out.println(str1 + ">" + str2);
32 } else if (str1.compareTo(str2) == 0) {
33 System.out.println(str1 + "=" + str2);
34 } else {
35 System.out.println(str1 + "<" + str2);
36 }
37
38 // compareToIgnoreCase()方法:忽略大小寫
39 if (str1.compareToIgnoreCase(str2) > 0) {
40 System.out.println(str1 + ">" + str2);
41 } else if (str1.compareToIgnoreCase(str2) == 0) {
42 System.out.println(str1 + "=" + str2);
43 } else {
44 System.out.println(str1 + "<" + str2);
45 }
46
47 // equals()方法:不忽略大小寫
48 if (str3.equals(str4)) {
49 System.out.println(str3 + "=" + str4);
50 } else {
51 System.out.println(str3 + "!=" + str4);
52 }
53
54 // equalsIgnoreCase()方法:忽略大小寫
55 if (str3.equalsIgnoreCase(str4)) {
56 System.out.println(str3 + "=" + str4);
57 } else {
58 System.out.println(str3 + "!=" + str4);
59 }
60 }
61
62 @Test // 字符串與其餘數據類型轉換
63 public void testConvert() {
64 /**
65 * 將字符串轉爲其餘數據類型
66 */
67 boolean bool = Boolean.getBoolean("false");
68 Integer integer = Integer.getInteger("20");
69 byte parseByte = Byte.parseByte("20");
70 float parseFloat = Float.parseFloat("20.2");
71 double parseDouble = Double.parseDouble("20.2");
72 Long long1 = Long.getLong("20");
73
74 /**
75 * 將其餘數據類型轉爲字符串:valueOf
76 */
77 String all = String.valueOf(bool);
78
79 }
80
81 @Test // 字符串查找
82 public void testFind() {
83 // 定義字符串
84 String str = "How qi bocome handsome like qi ge";
85
86 // indexOf(string, index):查找首個字符串出現的位置
87 System.out.println(str.indexOf("qi", 4));
88
89 // lastIndexOf(string, index):查找最後一個字符串出現的位置
90 System.out.println(str.lastIndexOf("qi", 10));
91
92 }
93
94 @Test // 字符串截取、拼接、替換和修改
95 public void testMain() {
96 // 定義字符串
97 String str = "How to cut and split strings";
98
99 // 截取指定索引範圍的字符串:substring(startIndex, endIndex)
100 System.out.println(str.substring(0, 10));
101
102 // 按照指定正則表達式拆分字符串:split(regex)
103 String[] split = str.split(",");
104 for (String string : split) {
105 System.err.println(string);
106 }
107
108 // 拼接字符串:concat(str)
109 System.out.println(str.concat("I'm OK") + "或者是" + str + "這樣也能夠拼接");
110
111 // 字符串替換:replace(oldStr, newStr)
112 System.out.println(str.replace("I'm OK", "I'm new string"));
113 }
114 }
3、時間日期類
1 package pers.mj;
2
3 import java.text.DateFormat;
4 import java.text.SimpleDateFormat;
5 import java.time.LocalDateTime;
6 import java.time.format.DateTimeFormatter;
7 import java.time.format.FormatStyle;
8 import java.util.Calendar;
9 import java.util.Date;
10
11 import org.junit.Test;
12
13 public class TestDate {
14 @Test // 日期實例化
15 public void testDate() {
16 // Date類:使用無參構造建立
17 Date date = new Date();
18 System.out.println(date.getTime()); // 時間戳:1592013149642
19
20 // Calendar類:靜態方法獲取實例
21 Calendar instance = Calendar.getInstance();
22 // 獲取年月日:MONTH默認0-11
23 System.out.println(instance.get(Calendar.YEAR) + "年 " + instance.get(Calendar.MONTH) + "月 "
24 + instance.get(Calendar.DATE) + "日");
25 // 設置年月日
26 instance.set(2020, 6, 13);
27 System.out.println(instance.get(Calendar.YEAR) + "年 " + instance.get(Calendar.MONTH) + "月 "
28 + instance.get(Calendar.DATE) + "日");
29
30 // LocalDateTime類:新增
31 // 使用靜態方法now()獲取當前時間日期
32 LocalDateTime ldt = LocalDateTime.now();
33 // 使用plusXxx(int x)增長指定字段的值
34 ldt.plusDays(1); // Day字段的值+1
35 // 使用minusXxx(int x)方法減小指定的字段的值
36 ldt.minusHours(1); // Hours字段的值-1
37 }
38
39 @Test // 日期格式化
40 public void testDateFormat() {
41 // DateFormat類:預約義格式,format(date)方法用來格式化
42 System.out.println(DateFormat.getDateInstance().format(new Date())); // 2020年6月13日
43 System.out.println(DateFormat.getTimeInstance().format(new Date())); // 上午11:13:42
44 System.out.println(DateFormat.getDateTimeInstance().format(new Date())); // 2020年6月13日 上午11:13:42
45
46 // SimpleDateFormat類:自定義格式自定日格式化日期,format(date)方法用來格式化
47 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
48 System.out.println(simpleDateFormat.format(new Date()));
49
50 // DateTimeFormatter類:前二者的結合體
51 // 預約義格式
52 DateTimeFormatter ofLocalizedDateTime = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL,
53 FormatStyle.FULL);
54 // 自定義格式
55 DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("y-M-d H:m:s");
56
57 // 實例化日期
58 LocalDateTime now = LocalDateTime.now();
59
60 System.out.println(ofLocalizedDateTime.format(now));
61 System.out.println(ofPattern.format(now));
62
63 }
64 }
4、正則表達式
1. 概念
1. Pattern類:編譯正則表達式,必須經過compile(pattern) 建立
2. Matcher類:對輸入字符串進行解釋和匹配操做的引擎,必須經過 pattern.matcher(str) 建立。
3. 捕獲組:把多個字符當一個單獨單元進行處理的方法,它經過對括號內的字符分組來建立,從左至右計算((A)(B(C))) 。
2. 操做
1. 經常使用方法
2. 經常使用方法代碼實現
1 package pers.mj;
2
3 import java.util.regex.Pattern;
4
5 public class TestRegex {
6 /***
7 * 校驗密碼強度
8 *
9 * @param pattern
10 * @return
11 */
12 public static boolean passwordRegex(String str) {
13 boolean flag = false;
14 flag = Pattern.matches("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,10}$", str);
15
16 return flag;
17 }
18
19 /***
20 * 校驗中文
21 *
22 * @param pattern
23 * @return
24 */
25 public static boolean chineseRegex(String str) {
26 boolean flag = true;
27 flag = Pattern.matches("^[\\u4e00-\\u9fa5]{0,}$", str);
28 return flag;
29 }
30
31 /***
32 * 由數字、26個英文字母或下劃線組成的字符串
33 *
34 * @param pattern
35 * @return
36 */
37 public static boolean pointRegex(String str) {
38 boolean flag = true;
39 flag = Pattern.matches("^\\w+$", str);
40 return flag;
41 }
42
43 /***
44 * 校驗E-Mail 地址
45 *
46 * @param pattern
47 * @return
48 */
49 public static boolean emailRegex(String str) {
50 boolean flag = true;
51 flag = Pattern.matches(
52 "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?",
53 str);
54 return flag;
55 }
56
57 /***
58 * 校驗身份證號碼 下面是身份證號碼的正則校驗。15 或 18位。
59 *
60 * @param pattern
61 * @return
62 */
63 public static boolean idCardRegex(String str) {
64 boolean flag = true;
65 if (str.length() == 15) {
66 flag = Pattern.matches("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$", str);
67 } else if (str.length() == 18) {
68 flag = Pattern.matches("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$",
69 str);
70 } else {
71 flag = false;
72 }
73
74 return flag;
75 }
76
77 /***
78 * 校驗日期 「yyyy-mm-dd「 格式的日期校驗,已考慮平閏年。
79 *
80 * @param pattern
81 * @return
82 */
83 public static boolean yearRegex(String str) {
84 boolean flag = true;
85 flag = Pattern.matches(
86 "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|"
87 + "(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$",
88 str);
89 return flag;
90 }
91
92 /***
93 * 校驗金額 金額校驗,精確到2位小數。
94 *
95 * @param pattern
96 * @return
97 */
98 public static boolean amountRegex(String str) {
99 boolean flag = true;
100 flag = Pattern.matches("^[0-9]+(.[0-9]{2})?$", str);
101 return flag;
102 }
103
104 /***
105 * 校驗手機號 下面是國內 1三、1五、18開頭的手機號正則表達式。(可根據目前國內收集號擴展前兩位開頭號碼)
106 *
107 * @param pattern
108 * @return
109 */
110 public static boolean telRegex(String str) {
111 boolean flag = true;
112 flag = Pattern.matches("^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$", str);
113 return flag;
114 }
115
116 /***
117 * 判斷IE的版本
118 *
119 * @param pattern
120 * @return
121 */
122 public static boolean ieVersionRegex(String str) {
123 boolean flag = true;
124 flag = Pattern.matches("^.*MSIE [5-8](?:\\.[0-9]+)?(?!.*Trident\\/[5-9]\\.0).*$", str);
125 return flag;
126 }
127
128 /***
129 * 校驗IP-v4地址
130 *
131 * @param pattern
132 * @return
133 */
134 public static boolean ipV4Regex(String str) {
135 boolean flag = true;
136 flag = Pattern.matches(
137 "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b",
138 str);
139 return flag;
140 }
141
142 /***
143 * 校驗IP-v6地址
144 *
145 * @param pattern
146 * @return
147 */
148 public static boolean ipV6Regex(String str) {
149 boolean flag = true;
150 flag = Pattern.matches(
151 "(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|"
152 + "([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]"
153 + "{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:"
154 + "((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]"
155 + "{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}"
156 + "[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}"
157 + "[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))",
158 str);
159 return flag;
160 }
161 }
六:集合
1、簡介
1. 做用:存儲引用類型數據,長度能夠動態的改變,解決了存儲數據數量不肯定的問題。
2. 架構:Java 集合框架主要包括兩種類型的容器,一種是集合(Collection),存儲一個元素集合,另外一種是圖(Map),存儲鍵/值對映射。
2、Collection 集合體系
1. 架構圖:存儲一組不惟一,無序的對象。
2. 經常使用方法
3. 不一樣集合的使用場景
4. 集合經常使用方法代碼實現
1 /**
2 * 建立學生類
3 */
4 class Student {
5 // 學號
6 private Integer id;
7 // 姓名
8 private String name;
9
10 public Student(Integer id, String name) {
11 this.id = id;
12 this.name = name;
13 }
14
15 @Override
16 public String toString() {
17 return "Student [id=" + id + ", name=" + name + "]";
18 }
19
20 }
21
22 public class TestCollection {
23 public static void main(String[] args) {
24 // 1. 建立集合存儲String類型數據
25 List<String> list = new ArrayList<String>();
26
27 // 2.向集合中添加元素
28 list.add("豬豬俠");
29 list.add("超人強");
30 list.add("波比");
31 list.add("小菲菲");
32
33 // 3. 遍歷集合
34 // 3.1普通for循環
35 String[] strArray = new String[list.size()];
36 list.toArray(strArray); // 將集合轉換爲數組
37 for (int i = 0; i < strArray.length; i++) {
38 System.out.println(strArray[i]);
39 }
40
41 // 3.2 foreach循環
42 for (String str : list) {
43 System.out.println(str);
44 }
45
46 // 3.3 迭代器遍歷
47 Iterator<String> iterator = list.iterator();
48 while (iterator.hasNext()) { // hasNext():判斷指針後是否有下一個元素
49 System.out.println(iterator.next()); // next():返回指針後的元素
50 }
51
52 // 4. 判斷集合中是否包含某元素
53 System.out.println(list.contains("小菲菲")); // true
54
55 // 5. 判斷集合是否爲空
56 System.out.println(list.isEmpty()); // false
57
58 // 6. 清除集合中全部元素
59 list.clear();
60 System.out.println(list.isEmpty()); // true
61 System.out.println("---------------------------------------------------");
62
63
64 // 建立集合存儲對象類型數據
65 List<Student> list2 = new ArrayList<Student>();
66
67 // 向集合中添加對象類型數據
68 list2.add(new Student(1, "張三"));
69 list2.add(new Student(2, "李四"));
70
71 // foreach遍歷集合
72 for (Student student : list2) {
73 System.out.println(student);
74 }
75
76 // 迭代器遍歷集合
77 Iterator<Student> iterator2 = list2.iterator();
78 while (iterator2.hasNext()) {
79 Student student = iterator2.next();
80 System.out.println(student);
81 }
82 }
83 }
3、Map 集合體系
1. 架構圖:存儲鍵值對象,提供key(鍵)到value(值)的映射。
2. 經常使用方法
3. 經常使用操做代碼實現
1 import java.util.HashMap;
2 import java.util.Iterator;
3 import java.util.Map;
4 import java.util.Map.Entry;
5
6 import javax.enterprise.inject.New;
7
8 class Teacher {
9 private String name;
10 private Integer age;
11
12 public Teacher(String name, Integer age) {
13 this.name = name;
14 this.age = age;
15 }
16
17 @Override
18 public String toString() {
19 return "Teacher [name=" + name + ", age=" + age + "]";
20 }
21
22 }
23
24 public class TestMap {
25 public static void main(String[] args) {
26 // 1. 建立Map集合存儲學號和姓名
27 Map<Integer, String> map = new HashMap<Integer, String>();
28
29 // 2. 向map集合中添加元素
30 map.put(1, "張三");
31 map.put(2, "李四");
32 map.put(3, "王五");
33
34 // 3. 遍歷map集合
35 // 3.1 經過map.keySet()遍歷集合
36 for (Integer key : map.keySet()) {
37 System.out.println("key=" + key + " value=" + map.get(key));
38 }
39
40 // 3.2 經過迭代器遍歷集合
41 Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
42 while (iterator.hasNext()) {
43 Map.Entry<Integer, String> entry = iterator.next();
44 System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());
45 }
46
47 // 3.3 經過map.entrySet()遍歷集合
48 for (Entry<Integer, String> entry : map.entrySet()) {
49 System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());
50 }
51
52 // 4. 判斷集合中是否包含指定鍵
53 System.out.println(map.containsKey("1")); // true
54 System.out.println(map.containsValue("list")); // false
55
56 // 5. 判斷集合是否爲空
57 System.out.println(map.isEmpty()); // false
58
59 // 6. 清除集合中全部元素
60 map.clear();
61 System.out.println(map.isEmpty()); // true
62
63 System.out.println("----------------------------------------");
64
65 // 1. 建立Map集合存儲對象類型數據
66 Map<Integer, Teacher> map2 = new HashMap<Integer, Teacher>();
67
68 // 2. 向Map集合中添加對象類型數據
69 map2.put(1, new Teacher("張三", 18));
70 map2.put(2, new Teacher("李四", 19));
71 map2.put(3, new Teacher("王五", 20));
72
73 // 3. 遍歷集合
74 // 3.1 經過map.keySet()遍歷:廣泛使用
75 for (Integer key : map2.keySet()) {
76 System.out.println("key=" + key + " value=" + map2.get(key));
77 }
78
79 // 3.2 經過迭代器遍歷集合
80 Iterator<Entry<Integer, Teacher>> iterator2 = map2.entrySet().iterator();
81 while (iterator2.hasNext()) {
82 Entry<Integer, Teacher> entry = iterator2.next();
83 System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());
84 }
85
86 // 3.3 經過map.entrySet()遍歷集合:推薦使用
87 for (Entry<Integer, Teacher> entry : map2.entrySet()) {
88 System.out.println("key=" + entry.getKey() + " value=" + entry.getValue());
89 }
90 }
91 }
七:IO流
1、
1. 流的概念:流是有起點和終點的一組有順序的字節集合,做用是進行數據傳輸
2. 流的分類
1. 按照數據流向不一樣能夠分爲輸入輸出流;
2. 按照處理數據單位不一樣能夠分爲字節流和字符流
3. 輸入流和輸出流的做用
1. 輸入流:程序從數據源讀取數據
2. 輸出流:將數據從程序中寫入指定文件
4. 字節流和字符流的做用
1. 字節流:以字節爲單位處理全部類型數據
2. 字符流:以字符爲單位處理純文本文件
2、體系結構
3、經常使用方法
4、經常使用方法實現文本文件複製
1 import java.io.FileInputStream;
2 import java.io.FileNotFoundException;
3 import java.io.FileOutputStream;
4 import java.io.FileReader;
5 import java.io.FileWriter;
6 import java.io.IOException;
7
8 /**
9 * 1. 文本文件複製
10 * @author DELL
11 *
12 */
13 public class TestIO {
14 public static void main(String[] args) {
15 // 要讀取的文件
16 String src = "E:/Workspaces1/Demo/src/TestFile.java";
17 // File src = new File("路徑");
18 // 要寫入的文件
19 String dest = "d:/test.java";
20
21 // 1.1 一次複製一個字節
22 copyFile1(src, dest);
23 // 1.2 一次複製一個字節數組
24 copyFile2(src, dest);
25
26 // 2.1 一次複製一個字符
27 copyFile3(src, dest);
28 // 2.2 一次複製一個字符數組
29 copyFile4(src, dest);
30 }
31
32 // 1. 一次複製一個字節,異常處理,手動關閉流
33 public static void copyFile1(String srcFileName, String destFileName) {
34 FileInputStream fis = null;
35 FileOutputStream fos = null;
36 try {
37 fis = new FileInputStream(srcFileName);
38 fos = new FileOutputStream(destFileName);
39 int cc = fis.read();
40 while (cc != -1) {
41 // 一次寫入一個字節
42 fos.write(cc);
43 // 一次寫入一個字節
44 cc = fis.read();
45 }
46 } catch (FileNotFoundException e) {
47 e.printStackTrace();
48 } catch (IOException e) {
49 e.printStackTrace();
50 } finally {
51 if (fos != null) {
52 try {
53 fos.close();
54 } catch (IOException e) {
55 e.printStackTrace();
56 }
57 }
58 if (fis != null) {
59 try {
60 fis.close();
61 } catch (IOException e) {
62 e.printStackTrace();
63 }
64 }
65 }
66 }
67
68 // 2. 一次複製一個字節數組,異常處理,自動關閉流
69 public static void copyFile2(String srcFileName, String destFileName) {
70 // 自動關閉流
71 try (
72 FileInputStream fis = new FileInputStream(srcFileName);
73 FileOutputStream fos = new FileOutputStream(destFileName);
74 ) {
75 byte[] bytes = new byte[1024];
76 int len = fis.read(bytes);
77 while (len != -1) {
78 // 一次寫入一個字節數組
79 fos.write(bytes, 0, len);
80 // 一次讀取一個字節數組
81 len = fis.read(bytes);
82 }
83 } catch (FileNotFoundException e) {
84 e.printStackTrace();
85 } catch (IOException e) {
86 e.printStackTrace();
87 }
88 }
89
90 // 3. 一次複製一個字符,異常處理,自動關閉流
91 public static void copyFile3(String srcFileName, String destFileName) {
92 try (
93 FileReader fr = new FileReader(srcFileName);
94 FileWriter fw = new FileWriter(destFileName);
95 ){
96 int cc = fr.read();
97 while (cc != -1) {
98 // 一次寫入一個字符
99 fw.write(cc);
100 // 一次讀取一個字符
101 cc = fr.read();
102 }
103 } catch (FileNotFoundException e) {
104 e.printStackTrace();
105 } catch (Exception e) {
106 e.printStackTrace();
107 }
108 }
109
110 // 4. 一次複製一個字符數組,異常處理,手動關閉流
111 public static void copyFile4(String srcFileName, String destFileName) {
112 FileReader fr = null;
113 FileWriter fw = null;
114 try {
115 fr = new FileReader(srcFileName);
116 fw = new FileWriter(destFileName);
117 char[] cbuf = new char[1024];
118 int len = fr.read(cbuf);
119 while (len != -1) {
120 // 一次寫入一個字符數組
121 fw.write(cbuf);
122 // 一次讀取一個字符數組
123 len = fr.read(cbuf);
124 }
125 } catch (FileNotFoundException e) {
126 e.printStackTrace();
127 } catch (IOException e) {
128 e.printStackTrace();
129 } finally {
130 if (fw != null) {
131 try {
132 fw.close();
133 } catch (IOException e) {
134 e.printStackTrace();
135 }
136 }
137 if (fr != null) {
138 try {
139 fr.close();
140 } catch (IOException e) {
141 e.printStackTrace();
142 }
143 }
144 }
145 }
146 }
5、序列化和反序列化
1. 序列化和反序列化的概念
1. 對象序列化:把對象轉換爲字節序列(二進制數據)的過程
2. 對象反序列化:把字節序列恢復爲對象的過程
2. 什麼狀況下須要序列化
1. 將對象保存到文件或數據庫中時
2. 使用套接字在網上傳送對象時
3. 經過RMI傳輸對象時
3. 如何實現序列化
1. 建立類實現Serializable接口
2. 指定serialVersionUID序列號
3. 使用對象輸出流(ObjectOutputStream)將對象保存到指定位置
4. 使用writerObject()方法將對象寫入到文件中
4. 哪些屬性不能被序列化
1. 使用transient修飾的屬性
2. 使用static修飾的屬性
5. 序列化和反序列化代碼實現
1 // 1. 建立類實現Serializable接口
2 class People implements Serializable {
3
4 // 2. 指定序列號
5 private static final long serialVersionUID = 1L;
6 // 靜態字段
7 private static String id = "2019";
8 // transient關鍵字修飾的字段
9 private transient String name;
10
11 private Integer age;
12
13 public String getName() {
14 return name;
15 }
16
17 public void setName(String name) {
18 this.name = name;
19 }
20
21 public Integer getAge() {
22 return age;
23 }
24
25 public void setAge(Integer age) {
26 this.age = age;
27 }
28
29 @Override
30 public String toString() {
31 return "People [name=" + name + ", age=" + age + "]";
32 }
33
34 }
35
36 public class Test {
37 public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
38 serializePeople();
39 deserializePeople();
40 }
41
42 /**
43 * 序列化
44 */
45 public static void serializePeople() throws FileNotFoundException, IOException {
46 People p = new People();
47 p.setName("張三");
48 p.setAge(18);
49 // 3. 使用對象輸出流將對象保存到指定位置
50 ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("D:/test.txt")));
51 // 4. 將對象寫入文件
52 oos.writeObject(p);
53 System.out.println("對象序列化成功!!");
54 oos.close();
55 }
56
57 /**
58 * 反序列化
59 */
60 public static People deserializePeople() throws ClassNotFoundException, IOException {
61 // 使用對象輸入流從指定位置讀取對象
62 ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("D:/test.txt")));
63 // 讀取對象
64 People p = (People) ois.readObject();
65 System.out.println("對象反序列化成功!!");
66 return p;
67
68 }
69 }
6、File 類經常使用方法
1 import java.io.File;
2 import java.io.FileFilter;
3 import java.io.IOException;
4 import java.text.SimpleDateFormat;
5
6 public class TestFile {
7 public static void main(String[] args) throws IOException {
8 // 1. 構造方法指明文件路徑以及格式
9 File file = new File("D:\\test2\\test.txt");
10 File file2 = new File("D:\\test2");
11 File file3 = new File("D:\\test3");
12
13 // 2.1 建立一個文件
14 file.createNewFile();
15 // 2.2 建立一個單級目錄
16 file2.mkdir();
17 // 2.3 建立一個多級目錄
18 file3.mkdirs();
19
20 // 3.1 判斷文件或文件夾是否存在
21 System.out.println(file.exists()); // true
22 // 3.2 判斷是否爲絕對路徑
23 System.out.println(file.isAbsolute()); // true
24 // 3.3 判斷是否爲文件
25 System.out.println(file2.isFile()); // false
26 // 3.4 判斷是否爲目錄
27 System.out.println(file2.isDirectory()); // true
28 // 3.5 判斷是否爲隱藏文件
29 System.out.println(file3.isHidden()); // false
30
31 // 4.1 獲取文件或目錄名稱
32 System.out.println(file.getName());
33 // 4.2 獲取文件的絕對路徑
34 System.out.println(file.getAbsolutePath());
35 // 4.3 獲取文件相對路徑
36 System.out.println(file.getPath());
37 // 4.4 獲取文件父目錄
38 System.out.println(file.getParent());
39 // 4.5 獲取文件大小
40 System.out.println(file.length());
41 // 4.6 獲取文件最後一次被修改時間
42 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
43 String updateTime = sdf.format(file.lastModified());
44 System.out.println(updateTime);
45
46 // 5.1 返回此目錄下的全部文件和目錄
47 String [] fileString = file2.list();
48 for (String str : fileString) {
49 System.out.println(str);
50 }
51 // 5.2 返回此目錄下的全部文件
52 File [] files = file2.listFiles();
53 for (File file4 : files) {
54 System.out.println(file4.getName());
55 }
56 // 5.3 返回全部根目錄
57 File [] files2 = File.listRoots();
58 for (File file4 : files2) {
59 System.out.println(file4);
60 }
61 // 5.4 返回指定目錄中符合過濾條件的文件和目錄
62 File [] files3 = file2.listFiles(new FileFilter() {
63
64 @Override
65 public boolean accept(File pathname) {
66 while ("a.txt".equals(pathname.getName())){
67 return true;
68 }
69 return false;
70 }
71 });
72 for (File file4 : files3) {
73 System.out.println(file4.getName());
74 }
75 }
76 }
八:多線程
1、簡介
1. 線程和進程
1. 進程:操做系統中的應用程序,一個進程就是一個應用程序
2. 線程:CPU調度的最小單元,進程的一個執行流
2. 上下文切換
1. 上下文切換:CPU從一個線程或進程切換到另外一個進程或線程;
2. 多線程程序並非同時進行的,因爲CPU的執行速度太快,CPU會在不一樣的線程之間快速的切換執行;
2、實現方式
1 import java.util.concurrent.Callable;
2 import java.util.concurrent.FutureTask;
3
4 /**
5 * 1. 建立多線程的三種方式
6 * 1. 繼承Thread類
7 *
8 * 2. 實現Runnable接口
9 * 1. 方式一:建立類實現Runnable接口
10 * 1. 建立類實現Runnable接口
11 * 2. 重寫run()方法
12 * 3. 使用Thread類的構造方法實例化實現Runnable接口的類對象
13 * 4. 開啓線程
14 *
15 * 2. 方式二:使用匿名內部類
16 * 1. 使用Thread類的構造方法建立一個Runnable接口的代理對象
17 * 2. 重寫run()方法
18 * 2. 開啓線程
19 *
20 * 3. 實現Callable接口
21 * 1. 方式一:建立類實現Callable接口
22 * 1. 建立類實現Callable接口
23 * 2. 重寫call()方法
24 * 3. 使用Thread類的構造方法實例化FutureTask對象
25 * 4. 使用FutureTask類的構造方法實例化實現了Callable接口的類對象
26 * 5. 開啓線程
27 *
28 * 2. 方式二:使用匿名內部類
29 * 1. 使用Thread類的構造方法實例化FutureTask對象
30 * 2. 使用FutureTask類的構造方法建立Callable接口的代理對象
31 * 3. 重寫call()方法
32 * 4. 開啓線程
33 *
34 * 2. 三種方式的優缺點
35 * 1. 繼承了Thread類
36 * 1. 優勢:代碼書寫簡單
37 * 2. 缺點:因爲Java的單繼承性,代碼的耦合度比較高
38 *
39 * 2. 實現了Runnable接口和Callable接口
40 * 1. 方式一:
41 * 1. 優勢:代碼的可擴展性更強
42 * 2. 缺點:沒有缺點
43 *
44 * 2. 方式二:
45 * 1. 優勢:代碼書寫簡單
46 * 2. 缺點:只適合線程使用一次的時候
47 */
48
49
50 /**
51 * 1. 繼承Thread類
52 */
53 class Thread1 extends Thread{
54 public static void test() {
55 for (int i = 0; i < 100; i++) {
56 System.out.println("繼承Thread類執行的第" + i + "次");
57 }
58 }
59 }
60
61 /**
62 * 2. 實現Runnable接口
63 */
64 class Thread2 implements Runnable{
65
66 @Override
67 public void run() {
68 for (int i = 0; i < 100; i++) {
69 System.out.println("實現Runnable接口方式一執行的第" + i + "次");
70 }
71 }
72 }
73
74 /**
75 * 3. 實現Callable接口
76 */
77 class Thread3 implements Callable<Integer>{
78 @Override
79 public Integer call() throws Exception {
80 int i = 0;
81 for (; i < 100; i++) {
82 System.out.println("實現Callable接口方式一執行的第" + i + "次");
83 }
84 return i;
85 }
86 }
87
88 public class TestThread {
89 public static void main(String[] args) {
90 // 1. 測試繼承Thread類
91 Thread1 thread1 = new Thread1();
92 thread1.start();
93 Thread1.test();
94
95
96 // 2. 測試實現Runnable接口
97 // 2.1 方式一
98 new Thread(new Thread2()).start();
99
100 // 2.2 方式二
101 new Thread(new Runnable() {
102 @Override
103 public void run() {
104 for (int i = 0; i < 100; i++) {
105 System.out.println("實現Runnable接口方式一執行的第" + i + "次");
106 }
107 }
108 }).start();
109
110
111 // 3. 測試實現Callable接口
112 // 3.1 方式一
113 new Thread(new FutureTask<Integer>(new Thread3() {
114 }), "方式三").start();;
115
116 // 3.2 方式二
117 new Thread(new FutureTask<Integer>(new Callable<Integer>() {
118 @Override
119 public Integer call() throws Exception {
120 int i = 0;
121 for (; i < 100; i++) {
122 System.out.println("實現Runnable接口方式二執行的第" + i + "次");
123 }
124 return i;
125 }
126 })).start();;
127 }
128 }
3、經常使用方法
1. 方法圖
2. 經常使用方法代碼實現
1 public class TestThreadMethod {
2 public static void main(String[] args) {
3 Thread thread = new Thread(new Runnable() {
4 @Override
5 public void run() {
6 for (int i = 0; i < 100; i++) {
7 // 獲取正在執行的線程對象的引用
8 System.out.println(Thread.currentThread().getName() + "執行的第" + i + "次");
9 }
10 }
11 });
12 // 1. 開啓線程
13 thread.start();
14
15
16 // 2. 設置
17 // 2.1 設置該線程名稱
18 thread.setName("線程1號");
19 // 2.2 設置該線程爲守護線程:main方法結束以後該線程中止
20 //thread.setDaemon(true);
21 // 2.3 設置該線程的優先級
22 thread.setPriority(7);
23
24
25 // 3. 獲取
26 // 3.1 獲取線程名稱
27 System.out.println(thread.getName()); // 線程1號
28 // 3.2 獲取線程標識符
29 System.out.println(thread.getId()); // 13
30 // 3.3 獲取線程優先級
31 System.out.println(thread.getPriority()); // 7
32 // 3.4 獲取線程狀態
33 System.out.println(thread.getState()); // RUNNABLE
34 // 3.5 獲取線程所在線程組
35 System.out.println(thread.getThreadGroup()); // java.lang.ThreadGroup[name=main,maxpri=10]
36
37
38 // 4. 判斷
39 // 4.1 判斷線程是否中斷
40 System.out.println(thread.isInterrupted()); // false
41 // 4.2 判斷線程是否爲活動狀態
42 System.out.println(thread.isAlive()); // true
43 // 4.3 判斷線程是否爲守護線程
44 System.out.println(thread.isDaemon()); // false
45
46
47 // 5. 停
48 // 5.1 讓線程休眠指定毫秒數
49 new Thread(new Runnable() {
50 @Override
51 public void run() {
52 for (int i = 0; i < 50; i++) {
53 System.out.println(Thread.currentThread().getName() + "執行的第" + i + "次");
54 if (i == 25) {
55 try {
56 /**
57 * 1. sleep()是靜態方法
58 * 2. sleep()使用時必須捕獲異常
59 * 3. sleep()執行時,只是讓該線程進入阻塞狀態,並不會釋放鎖
60 */
61 System.out.println("線程2號正在休眠");
62 Thread.sleep(5000);
63 } catch (InterruptedException e) {
64 e.printStackTrace();
65 }
66 }
67 }
68 }
69 },"線程2號").start();
70
71 // 5.2 暫停當前線程去執行其餘線程
72 new Thread(new Runnable() {
73 @Override
74 public void run() {
75 for (int i = 0; i < 50; i++) {
76 System.out.println(Thread.currentThread().getName() + "執行了" + i + "次");
77 if (i == 25) {
78 /**
79 * 1. yield()是靜態方法
80 * 2. yield()執行時,讓線程進入就緒狀態,從新爭搶CPU執行權,並不會釋放鎖
81 */
82 Thread.yield();
83 }
84 }
85 }
86 },"線程3號").start();
87
88 // 5.3 等待線程銷燬
89 new Thread(new Runnable() {
90 @Override
91 public void run() {
92 for (int i = 0; i < 100; i++) {
93 if (i == 50) {
94 /**
95 * 1. join()是對象方法
96 * 2. join()使用時必須捕獲異常
97 * 3. join()使用場景:一個執行完的線程須要另外一個正在執行的線程的運行結果時
98 */
99 System.out.println("線程1號正在銷燬!!!!");
100 try {
101 thread.join();
102 } catch (InterruptedException e) {
103 e.printStackTrace();
104 }
105 System.out.println("線程1號銷燬成功!!!!");
106 }
107 }
108 }
109 },"線程4號").start();
110
111 }
112 }
4、線程同步
1 import java.util.concurrent.locks.Lock;
2 import java.util.concurrent.locks.ReentrantLock;
3
4
5 /**
6 * 1. 線程安全
7 * 1. 什麼是線程安全:當多個線程同時操做同一共享數據時,致使共享數據出錯
8 * 2. 怎樣解決:使用線程同步技術
9 *
10 * 2. 線程同步:將多個線程的數據共享
11 *
12 * 3. 實現線程同步的方式
13 * 1. 同步代碼塊:有synchronized關鍵字修飾的語句塊
14 * 1. 實例代碼塊:鎖對象是this或者任意對象
15 * 2. 靜態代碼塊:鎖對象是當前類的字節碼文件
16 *
17 * 2. 同步方法: 有synchronized關鍵字修飾的方法
18 * 1. 實例方法
19 * 2. 靜態方法
20 *
21 * 3. 使用重入鎖
22 * 1. 聲明鎖對象
23 * 2. 給共享數據上鎖
24 * 3. 在finally中解鎖
25 *
26 * 4. wait()和notify()
27 * wait(): 線程等待,釋放鎖
28 * notify(): 喚醒等待狀態線程
29 */
30
31 class Bank{
32 // 實例帳戶
33 private Integer account1 = 100;
34 // 靜態帳戶
35 private static Integer account2 = 100;
36 // 1. 聲明鎖對象
37 private Lock lock = new ReentrantLock();
38
39
40
41 /**
42 * 1. 同步代碼塊
43 */
44 // 存錢1
45 public void save1(Integer money) {
46 // 實例代碼塊
47 synchronized (this) {
48 account1 += money;
49 }
50 System.out.println(Thread.currentThread().getName() + "存入了" + money + "元");
51 }
52 // 取錢1
53 public void draw1(Integer money) {
54 // 實例代碼塊
55 synchronized (this) {
56 if (account1 - money < 0) {
57 System.out.println("帳戶餘額不足");
58 return;
59 }
60 account1 -= money;
61 System.out.println(Thread.currentThread().getName() + "取出了" + money + "元");
62 }
63 }
64 // 存錢2
65 public static void save2(Integer money) {
66 // 靜態代碼塊
67 synchronized (Bank.class) {
68 account2 += money;
69 }
70 System.out.println(Thread.currentThread().getName() + "存入了" + money + "元");
71 }
72 // 取錢2
73 public static void draw2(Integer money) {
74 // 靜態代碼塊
75 synchronized (Bank.class) {
76 if (account2 - money < 0) {
77 System.out.println("餘額不足");
78 return;
79 }
80 account2 -= money;
81 System.out.println(Thread.currentThread().getName() + "取出了" + money + "元");
82 }
83 }
84
85 /**
86 * 2. 同步方法
87 */
88 // 2.1 實例方法
89 public synchronized void save3(Integer money) {
90 account1 += money;
91 System.out.println(Thread.currentThread().getName() + "存入了" + money + "元");
92 }
93 public synchronized void draw3(Integer money) {
94 if (account1 - money < 0) {
95 System.out.println("餘額不足");
96 return;
97 }
98 account1 -= money;
99 System.out.println(Thread.currentThread().getName() + "取出了" + money + "元");
100 }
101
102 // 2.2 靜態方法
103 public synchronized static void save4(Integer money) {
104 account2 += money;
105 System.out.println(Thread.currentThread().getName() + "存入了" + money + "元");
106 }
107 public synchronized static void draw4(Integer money) {
108 if (account2 - money < 0) {
109 System.out.println("餘額不足");
110 return;
111 }
112 account2 -= money;
113 System.out.println(Thread.currentThread().getName() + "取出了" + money + "元");
114 }
115
116
117 /**
118 * 3. 重入鎖
119 */
120 public void save5(Integer money) {
121 // 2. 上鎖
122 lock.lock();
123 try {
124 account1 += money;
125 System.out.println(Thread.currentThread().getName() + "存入了" + money + "元");
126 } finally {
127 // 3. 解鎖
128 lock.unlock();
129 }
130 }
131 public void draw5(Integer money) {
132 // 2. 上鎖
133 lock.lock();
134 try {
135 if (account1 - money < 0) {
136 System.out.println("餘額不足");
137 return;
138 }
139 account1 -= money;
140 System.out.println(Thread.currentThread().getName() + "取出了" + money + "元");
141 } finally {
142 // 3. 解鎖
143 lock.unlock();
144 }
145 }
146
147 // 查看帳戶餘額
148 public void show() {
149 System.out.println("實例帳戶餘額" + account1);
150 System.out.println("靜態帳戶餘額" + account2);
151 }
152
153 }
154
155 class Demo implements Runnable{
156 private static Bank bank = new Bank();
157 @Override
158 public void run() {
159 /**
160 * 1. 測試同步代碼塊
161 */
162 // 1.1 實例代碼塊
163 bank.save1(100);
164 bank.show();
165 bank.draw1(20);
166 bank.show();
167
168 // 1.2 靜態代碼塊
169 Bank.save2(100);
170 bank.show();
171 Bank.draw2(20);
172 bank.show();
173
174 /**
175 * 2. 測試同步方法
176 */
177 // 2.1 實例方法
178 bank.save3(100);
179 bank.show();
180 bank.draw3(20);
181 bank.show();
182 // 2.2 靜態方法
183 Bank.save4(100);
184 bank.show();
185 Bank.draw4(20);
186 bank.show();
187
188 /**
189 * 3. 測試重入鎖
190 */
191 bank.save5(100);
192 bank.show();
193 bank.draw5(20);
194 bank.show();
195 }
196 }
197
198 public class TestSynchronized {
199 public static void main(String[] args) {
200 // 1. 測試同步實例代碼塊
201 new Thread(new Demo(),"線程1號").start();
202 // 2. 測試同步靜態代碼塊
203 new Thread(new Demo(),"線程2號").start();
204
205 // 2. 測試同步方法
206 // 2.1 實例方法
207 new Thread(new Demo(),"線程3號").start();
208 // 2.2 靜態方法
209 new Thread(new Demo(),"線程4號").start();
210
211 // 3. 測試衝入鎖
212 new Thread(new Demo(),"線程5號").start();
213
214 }
215 }
5、線程控制(線程狀態轉換圖)
九:網絡編程
1、簡介
1. 概述
1. 計算機網絡:多臺算機之間實現信息傳遞和資源共享的的計算機系統
2. 網絡編程:不一樣計算機之間使用網絡進行數據交換
2. 三要素
1. IP:每一個設備在網絡中的惟一標識
2. 端口號:每一個程序在設備上的惟一標識
3. 協議:在網絡中進行數據交換要遵照的規則
3. UDP與TCP的區別
1. UDP:面向無鏈接,數據不可靠,速度快,適用於高速傳輸和對實時性要求較高
2. TCP:面向鏈接,數據可靠,速度略低,適用於可靠傳輸
2、操做
1. 經常使用方法
2. UDP傳輸代碼實現
1 import java.io.IOException;
2 import java.net.DatagramPacket;
3 import java.net.DatagramSocket;
4 import java.net.SocketException;
5
6 /**
7 * 1. 服務器端實現步驟
8 * 1. 建立服務器對象
9 * 2. 將接受到的數據打包
10 * 3. 將數據包存儲到服務器對象
11 * 4. 打印數據
12 * 5. 關閉流通道
13 *
14 * 2. 客戶端步驟實現
15 * 1. 建立客戶端對象
16 * 2. 將數據打包
17 * 3. 發送數據包
18 * 4. 關閉流通道
19 *
20 * @author 萌萌哥的春天
21 *
22 */
23
24
25 /**
26 * 服務器端
27 */
28 public class Server {
29 public static void main(String[] args) throws IOException {
30 // 1. 建立服務器對象
31 DatagramSocket ds = new DatagramSocket(9102);
32
33 // 2. 將接收到的數據打包
34 byte[] bytes = new byte[1024];
35 DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
36
37 // 3. 將數據包存入服務器對象
38 ds.receive(dp);
39
40 // 4. 打印數據
41 String IP = dp.getAddress().getHostAddress(); // IP地址
42 int port = dp.getPort();
43 String data = new String(dp.getData(), 0, dp.getLength()); // 將字節數組轉爲字符串
44 System.out.println(IP+": --" + data + "--" + port + ":");
45
46 // 5. 關閉流通道
47 ds.close();
48 }
49 }
50
51 /**
52 * 客戶端
53 */
54 public class Client {
55 public static void main(String[] args) throws IOException {
56 // 1. 建立客戶端對象
57 DatagramSocket ds = new DatagramSocket();
58
59 // 2. 將數據打包
60 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // 接受鍵盤輸入
61 byte[] bytes = br.toString().getBytes(); // 將字符串轉換爲字節數組
62 DatagramPacket dp = new DatagramPacket(bytes, bytes.length, InetAddress.getByName("localhost"),9102);
63
64 // 3. 發送數據包
65 ds.send(dp);
66
67 // 4. 關閉流通道
68 ds.close();
69 }
70 }
1 import java.io.BufferedWriter;
2 import java.io.BufferedReader;
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.io.InputStreamReader;
9 import java.io.OutputStreamWriter;
10 import java.net.ServerSocket;
11 import java.net.Socket;
12 import java.net.UnknownHostException;
13
14 /**
15 * 1. 服務器端實現步驟
16 * 1. 建立服務器對象
17 * 2. 偵聽客戶端鏈接
18 * 3. 使用輸入流讀取客戶端輸入
19 * 4. 使用輸出流寫入文件
20 * 5. 使用輸出流通知客戶端
21 * 6. 關閉流通道
22 *
23 * 2. 客戶端步驟實現
24 * 1. 建立客戶端對象
25 * 2. 使用輸出流發送數據到服務器
26 * 3. 使用輸入流讀取本地文件
27 * 4. 使用輸入流接收服務器反饋並打印到控制檯
28 * 5. 關閉流通道
29 *
30 * @author 萌萌哥的春天
31 *
32 */
33
34
35 /**
36 * 服務器端
37 */
38 public class Server {
39 private static ServerSocket server;
40 private static Socket socket;
41 private static InputStream in;
42 private static OutputStream out;
43
44 public static void main(String[] args) {
45 try {
46 // 1. 建立服務器對象
47 server = new ServerSocket(9102);
48
49 // 2. 偵聽客戶端鏈接
50 socket = server.accept();
51
52 // 3. 使用輸入流接收客戶端輸入
53 in = socket.getInputStream();
54
55 // 4. 使用輸出流寫入文件
56 out = new FileOutputStream("D:/server.txt");
57 byte[] bytes = new byte[1024];
58 int len = 0;
59 while ((len = in.read(bytes)) != -1) {
60 out.write(bytes, 0, len);
61 out.flush();
62 }
63
64 // 5. 使用輸出流通知客戶端
65 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
66 bw.write("文件上傳成功");
67 bw.flush();
68
69 } catch (FileNotFoundException e) {
70 e.printStackTrace();
71 } catch (IOException e) {
72 e.printStackTrace();
73 } finally {
74 // 6. 關閉流通道
75 if (server != null) {
76 try {
77 server.close();
78 } catch (IOException e) {
79 e.printStackTrace();
80 }
81 }
82 if (socket != null) {
83 try {
84 socket.close();
85 } catch (IOException e) {
86 e.printStackTrace();
87 }
88 }
89 if (in != null) {
90 try {
91 in.close();
92 } catch (IOException e) {
93 e.printStackTrace();
94 }
95 }
96 if (out != null) {
97 try {
98 out.close();
99 } catch (IOException e) {
100 e.printStackTrace();
101 }
102 }
103 }
104 }
105 }
106
107 /**
108 * 客戶端
109 */
110 public class Client {
111 private static Socket socket;
112 private static InputStream in;
113
114 public static void main(String[] args) {
115 try {
116 // 1. 建立客戶端對象
117 socket = new Socket("localhost", 9102);
118
119 // 2. 使用輸入流發送數據到服務器
120 OutputStream out = socket.getOutputStream();
121
122 // 3. 使用輸入流讀取本地文件
123 in = new FileInputStream("D:/client.txt");
124 byte[] bytes = new byte[1024];
125 int len = 0;
126 while ((len = in.read(bytes)) != -1) {
127 out.write(bytes, 0, len);
128 }
129
130 // 4. 通知服務器文件已上傳
131 socket.shutdownOutput();
132
133 // 5. 使用輸出流接收服務器反饋
134 BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
135 System.out.println(br.readLine());
136
137 } catch (UnknownHostException e) {
138 e.printStackTrace();
139 } catch (FileNotFoundException e) {
140 e.printStackTrace();
141 } catch (IOException e) {
142 e.printStackTrace();
143 } finally {
144 // 6. 關閉流通道
145 if (socket != null) {
146 try {
147 socket.close();
148 } catch (IOException e) {
149 e.printStackTrace();
150 }
151 }
152 if (in != null) {
153 try {
154 in.close();
155 } catch (IOException e) {
156 e.printStackTrace();
157 }
158 }
159 }
160 }
161 }
十:反射
1、概述
1. 反射機制:動態獲取類的信息和調用對象的方法的功能
2. 反射實現:獲取每一個類的字節碼文件,也就是Class類對象
2、反射的方式
1 /**
2 * 反射的三種方式:推薦2和3
3 * 1. Object類的getClass()方法
4 * 2. 實體類.class
5 * 3. Class類的forName()方法
6 */
7
8
9 public class TestReflect {
10 public static void main(String[] args) {
11 // 1. 方式一:getClass()方法
12 Worker worker = new Worker();
13 Class<? extends Worker> class1 = worker.getClass();
14 System.out.println(class1.getName()); // Worker
15
16 // 2. 方式二:實體類.class
17 Class<Worker> class2 = Worker.class;
18 System.out.println(class1 == class2); // true
19
20 // 3. 方式三:Class類的forName()方法
21 try {
22 Class<?> class3 = Class.forName("Worker");
23 System.out.println(class2 == class3); // true
24 } catch (ClassNotFoundException e) {
25 e.printStackTrace();
26 }
27 }
28 }
3、操做
1. 經常使用方法
2. 經常使用方法代碼實現
1 import java.lang.reflect.Constructor;
2 import java.lang.reflect.Field;
3 import java.lang.reflect.Method;
4
5 class Worker {
6 // 私有屬性
7 private Integer id;
8 private String name;
9 // 公共屬性
10 Integer age;
11
12 public Worker() {
13 }
14
15 public Worker(String name) {
16 this.name = name;
17 }
18
19 protected Worker(Integer id, String name) {
20 this.id = id;
21 this.name = name;
22 }
23
24 private Worker(Integer id, String name, Integer age) {
25 this.id = id;
26 this.name = name;
27 this.age = age;
28 }
29
30 // 繼承方法
31 @Override
32 public String toString() {
33 return "Worker [id=" + id + ", name=" + name + ", age=" + age + "]";
34 }
35
36 // 私有方法
37 private void test() {
38 System.out.println("這是私有方法");
39 }
40
41 }
42
43 public class TestReflect {
44 public static void main(String[] args) {
45 // 1. 建立Class對象
46 Class<Worker> class1 = Worker.class;
47 Class<String> class2 = String.class;
48
49
50 /**
51 * 2. 類相關操做
52 */
53
54 // 2.1 獲取完整性類名
55 System.out.println(class2.getName()); // java.lang.String
56
57 // 2.2 獲取類名
58 System.out.println(class2.getSimpleName()); // String
59
60 // 2.3 獲取此類的包名
61 System.out.println(class2.getPackage()); // package java.lang
62
63 // 2.4 獲取當前類所繼承父類的名字
64 System.out.println(class2.getSuperclass()); // class java.lang.Object
65
66 // 2.5獲取當前類實現的接口
67 Class<?>[] interfaces = class2.getInterfaces();
68 for (Class<?> class3 : interfaces) {
69 System.out.println(class3);
70 // interface java.io.Serializable
71 // interface java.lang.Comparable
72 // interface java.lang.CharSequence
73 }
74
75
76 /**
77 * 3. 類中屬性相關操做
78 */
79
80 // 3.1 獲取指定屬性
81 try {
82 Field declaredField = class1.getDeclaredField("name");
83 System.out.println(declaredField); // private java.lang.String Worker.name
84 } catch (NoSuchFieldException e) {
85 e.printStackTrace();
86 } catch (SecurityException e) {
87 e.printStackTrace();
88 }
89
90 // 3.2 獲取全部屬性
91 Field[] declaredFields = class1.getDeclaredFields();
92 for (Field field : declaredFields) {
93 System.out.println(field);
94 // private java.lang.Integer Worker.id
95 // private java.lang.String Worker.name
96 // java.lang.Integer Worker.age
97 }
98
99
100 /**
101 * 4. 類中構造方法相關操做
102 */
103
104 // 4.1 獲取參數列表匹配的構造方法
105 try {
106 Constructor<Worker> declaredConstructor = class1.getDeclaredConstructor(Integer.class, String.class, Integer.class);
107 System.out.println(declaredConstructor); // private Worker(java.lang.Integer,java.lang.String,java.lang.Integer)
108 System.out.println(class1.getDeclaredConstructor(String.class)); // public Worker(java.lang.String)
109 } catch (NoSuchMethodException e) {
110 e.printStackTrace();
111 } catch (SecurityException e) {
112 e.printStackTrace();
113 }
114
115 // 4.2 獲取類中全部公共構造方法
116 Constructor<?>[] constructors = class1.getConstructors();
117 for (Constructor<?> constructor : constructors) {
118 System.out.println(constructor);
119 // public Worker(java.lang.String)
120 // public Worker()
121 }
122
123 // 4.3 獲取類中全部構造方法
124 Constructor<?>[] declaredConstructors = class1.getDeclaredConstructors();
125 for (Constructor<?> constructor : declaredConstructors) {
126 System.out.println(constructor);
127 // private Worker(java.lang.Integer,java.lang.String,java.lang.Integer)
128 // protected Worker(java.lang.Integer,java.lang.String)
129 // public Worker(java.lang.String)
130 // public Worker()
131 }
132
133 /**
134 * 5. 類中方法相關操做
135 */
136
137 // 5.1 獲取方法名和參數列表都匹配的方法
138 try {
139 Method declaredMethod = class1.getDeclaredMethod("toString");
140 System.out.println(declaredMethod); // public java.lang.String Worker.toString()
141 System.out.println(class1.getDeclaredMethod("test")); // //private void Worker.test()
142 } catch (NoSuchMethodException e) {
143 e.printStackTrace();
144 } catch (SecurityException e) {
145 e.printStackTrace();
146 }
147
148 // 5.2 獲取類中全部公共方法
149 Method[] methods = class1.getMethods();
150 for (Method method : methods) {
151 System.out.println(method); // 當前類方法和它所繼承的類及其實現的接口中的全部公共方法
152 }
153
154 // 5.3 獲取當前類中全部方法
155 Method[] declaredMethods = class1.getDeclaredMethods();
156 for (Method method : declaredMethods) {
157 System.out.println(method);
158 // public java.lang.String Worker.toString()
159 // private void Worker.test()
160 }
161
162 }
163 }
1 import java.lang.reflect.Field;
2 import java.lang.reflect.Method;
3
4 class Worker {
5 // 私有屬性
6 private Integer id;
7 private String name;
8 // 公共屬性
9 public Integer age;
10
11 public Worker() {
12 }
13
14 @Override
15 public String toString() {
16 return "Worker [id=" + id + ", name=" + name + ", age=" + age + "]";
17 }
18
19 // 私有方法
20 private void test() {
21 System.out.println("這是私有方法");
22 }
23
24 // 公共方法
25 public void show() {
26 System.out.println("這是公共方法");
27 }
28 }
29
30 public class TestReflect {
31 public static void main(String[] args) throws Exception {
32 // 1. 建立Class對象
33 Class<?> class1 = Class.forName("Worker");
34
35 // 2. 經過構造方法實例化類對象
36 Object obj = class1.getConstructor().newInstance();
37
38 // 3. 給公共屬性設置值
39 Field field1 = class1.getField("age");
40 field1.set(obj, 18);
41
42 // 4. 給私有屬性設置值
43 Field field = class1.getDeclaredField("name");
44 field.setAccessible(true); // 解除私有限定
45 field.set(obj, "張三"); // 爲Worker類中的name屬性設置值
46
47 // 5. 調用公共成員方法
48 Method method1 = class1.getMethod("show");
49 method1.invoke(obj);
50
51 // 6. 調用私有成員方法
52 Method method = class1.getDeclaredMethod("test");
53 method.setAccessible(true);
54 method.invoke(obj); // 第一個參數是類對象,其他的爲實參
55 System.out.println(obj);
56 }
57 }