基礎語法

1. Hello World

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
講解

這是一個典型的Java程序,它定義了一個名為HelloWorld的類,該類包含一個main方法——Java應用程序的入口點。System.out.println("Hello, World!");打印出"Hello, World!"到控制枱。

2. 數據類型

int a = 100;
float b = 5.25f;
double c = 5.25;
boolean d = true;
char e = 'A';
String f = "Hello";
講解

此代碼片段展示了Java中的基本數據類型。int是整數,floatdouble是浮點數,boolean是布爾類型,char用於單個字符,String用於字符串。

3. 條件判斷

if (a > b) {
    // 條件成立時執行
} else if (a == b) {
    // 另一個條件
} else {
    // 條件都不成立時執行
}
講解

使用條件判斷來執行不同的代碼塊。if-else的結構幫助程序做出選擇,執行基於不同條件的代碼。

4. 循環結構

for循環
for (int i = 0; i < 10; i++) {
    System.out.println("i: " + i);
}
講解

for循環允許在滿足某個條件時重複執行代碼。這裏的for循環從0開始,打印到9。

while循環
int i = 0;
while (i < 10) {
    System.out.println("i: " + i);
    i++;
}
講解

while循環在一個條件成立時不斷執行一段代碼。只要i小於10,就會繼續循環。

do-while循環
int i = 0;
do {
    System.out.println("i: " + i);
    i++;
} while (i < 10);
講解

do-while循環與while循環相似,但它在先執行一次代碼之後,才檢查條件。

5. 數組

int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
// ...
int[] arr2 = {1, 2, 3, 4, 5};
講解

數組是用於存儲同一類型元素的集合。int[] arr是一個整數數組,arr2是一個帶初始化的數組。

6. 方法定義與調用

public static int add(int a, int b) {
    return a + b;
}
int sum = add(5, 3); // 調用方法
講解

方法是可重用的代碼段。add是一個方法,它接收兩個整數參數並返回它們的和。通過調用add(5, 3)獲取結果。

面向對象編程

7. 類與對象

public class Dog {
    String name;

    public void bark() {
        System.out.println(name + " says: Bark!");
    }
}

Dog myDog = new Dog();
myDog.name = "Rex";
myDog.bark();
講解

Dog類具有屬性name和方法bark。通過創建Dog對象並設置其屬性, 可以調用其方法。

8. 構造方法

public class User {
    String name;

    public User(String newName) {
        name = newName;
    }
}

User user = new User("Alice");
講解

構造方法用於對象初始化。在User類中,構造函數賦值name為傳入的參數。

9. 繼承

public class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

public class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

Dog dog = new Dog();
dog.eat(); // 繼承自Animal
dog.bark();
講解

繼承允許類繼承其他類的屬性和方法。Dog繼承Animal,因此可以調用eat方法。

10. 接口

public interface Animal {
    void eat();
}

public class Dog implements Animal {
    public void eat() {
        System.out.println("The dog eats.");
    }
}

Dog dog = new Dog();
dog.eat();
講解

接口定義類須實現的方法。Dog類實現Animal接口,需要具體化eat方法。

11. 抽象類

public abstract class Animal {
    abstract void eat();
}

public class Dog extends Animal {
    void eat() {
        System.out.println("The dog eats.");
    }
}

Animal dog = new Dog();
dog.eat();
講解

抽象類可以包含抽象方法,子類必須實現這些方法。Dog類實現抽象類Animaleat方法。

12. 方法重載

public class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    double add(double a, double b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }
}

Calculator calc = new Calculator();
calc.add(5, 3); // 調用第一個方法
calc.add(5.0, 3.0); // 調用第二個方法
calc.add(5, 3, 2); // 調用第三個方法
講解

方法重載允許在同一類中創建多個同名方法,但參數類型或數量不同。Java選擇最匹配的簽名。

13. 方法重寫

public class Animal {
    void makeSound() {
        System.out.println("Some sound");
    }
}

public class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}

Animal myDog = new Dog();
myDog.makeSound(); // 輸出 "Bark"
講解

重寫允許子類提供父類方法的新實現。在Dog中,makeSound方法重寫了Animal類的方法。

14. 多態

public class Animal {
    void makeSound() {
        System.out.println("Some generic sound");
    }
}

public class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Bark");
    }
}

public class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Meow");
    }
}

Animal myAnimal = new Dog();
myAnimal.makeSound(); // Bark
myAnimal = new Cat();
myAnimal.makeSound(); // Meow
講解

多態允許一個對象表現為多種類型。makeSound方法可由Animal類型引用調用,並根據對象類型改變行為。

15. 封裝

public class Account {
    private double balance;

    public Account(double initialBalance) {
        if(initialBalance > 0) {
            balance = initialBalance;
        }
    }

    public void deposit(double amount) {
        if(amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if(amount <= balance) {
            balance -= amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}

Account myAccount = new Account(50);
myAccount.deposit(150);
myAccount.withdraw(75);
System.out.println(myAccount.getBalance()); // 應輸出:125.0
講解

封裝通過隱藏類信息實現。使用private變量限制直接訪問,提供公共方法來調整內部狀態。

16. 靜態變量和方法

public class MathUtils {
    public static final double PI = 3.14159;

    public static double add(double a, double b) {
        return a + b;
    }

    public static double subtract(double a, double b) {
        return a - b;
    }

    public static double multiply(double a, double b) {
        return a * b;
    }
}

double circumference = MathUtils.PI * 2 * 5;
System.out.println(circumference); // 打印圓的周長
講解

靜態變量和方法屬於類本身,而不屬於單一對象。可以直接用類名.方法進行調用,例如計算圓周長。

17. 內部類

public class OuterClass {
    private String msg = "Hello";

    class InnerClass {
        void display() {
            System.out.println(msg);
        }
    }

    public void printMessage() {
        InnerClass inner = new InnerClass();
        inner.display();
    }
}

OuterClass outer = new OuterClass();
outer.printMessage(); // 輸出 "Hello"
講解

內部類是定義在另一個類中的類。提供從內部訪問外部類成員的權限。用於封裝邏輯相關的類。

18. 匿名類

abstract class SaleTodayOnly {
    abstract int dollarsOff();
}

public class Store {
    public SaleTodayOnly sale = new SaleTodayOnly() {
        int dollarsOff() {
            return 3;
        }
    };
}

Store store = new Store();
System.out.println(store.sale.dollarsOff()); // 應輸出3
講解

匿名類允許創建沒有名字的類實例。這些類通常用於簡化一次性使用,定義新的子類或實現接口。

高級編程概念

19. 泛型

public class Box<T> {
    private T t;

    public void set(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }
}

Box<Integer> integerBox = new Box<>();
integerBox.set(10);
System.out.println(integerBox.get()); // 應輸出:10
講解

泛型提供一種創建類型安全的代碼方式,允許類、接口和方法在實現中使用類型參數。這樣可避免類型轉換錯誤。

20. 集合框架

ArrayList
import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
System.out.println(list); // 應輸出:[Java, Python, C++]
講解

ArrayList是一個動態數組,允許根據需要調整大小。非常適合用於需要頻繁添加和刪除的場景。

HashMap
import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Cherry", 3);
System.out.println(map.get("Apple")); // 應輸出:1
講解

HashMap是一種基於哈希表的數據結構,提供鍵與值的映射。高效支持基本操作如插入、檢索、刪除。

21. 異常處理

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
} finally {
    System.out.println("This will always be printed.");
}
講解

Java支持異常處理以捕獲和處理錯誤。try-catch-finally塊用於檢測錯誤並執行備用代碼,確保某些操作無論是否發生異常都執行。

22. 文件I/O

讀取文件
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

String line;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}
講解

文件I/O用於讀寫文件。此代碼使用BufferedReaderFileReader讀取文件,捕獲和處理IO異常,以便安全進行文件操作。

寫入文件
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
    bw.write("Hello World!");
} catch (IOException e) {
    e.printStackTrace();
}
講解

文件寫入也使用了try-with-resources,確保在寫入後自動關閉BufferedWriter,處理IO異常,保證寫入的安全和完整性。

23. 多線程

創建線程
class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread running");
    }
}

MyThread myThread = new MyThread();
myThread.start();
講解

繼承Thread類並覆蓋run方法可以創建新線程。通過調用start方法啓動線程,執行run中的代碼。

實現Runnable接口
class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable running");
    }
}

Thread thread = new Thread(new MyRunnable());
thread.start();
講解

實現Runnable接口是創建線程的另一種方式。將Runnable實例傳遞給Thread構造方法並調用start

24. 同步

public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}
講解

同步確保線程安全訪問共享資源。synchronized關鍵字用於鎖定代碼塊,以防止多個線程同時訪問,以便保證數據一致性。

25. 高級多線程

使用Executors
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService executor = Executors.newFixedThreadPool(2);

executor.submit(() -> {
    System.out.println("ExecutorService running");
});

executor.shutdown();
講解

Executors提供一個框架來控制線程池。用於管理線程的創建和安排,優化多線程任務執行。

Future和Callable
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

Callable<Integer> callableTask = () -> {
    return 10;
};

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Integer> future = executorService.submit(callableTask);

try {
    Integer result = future.get(); // this will wait for the task to finish
    System.out.println("Future result: " + result);
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
} finally {
    executorService.shutdown();
}
講解

Callable可以返回結果和拋出異常。結合Future和線程池可以執行耗時任務,並在以後獲取結果或處理異常,是構建併發應用的實用工具。

26. 線程池

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);

for (int i = 0; i < 10; i++) {
    fixedThreadPool.execute(() -> {
        System.out.println("Running in thread: " + Thread.currentThread().getName());
    });
}

fixedThreadPool.shutdown();
講解

線程池管理線程的創建和銷燬,允許重用現有的線程來處理多個任務,以減少開銷並提高性能。newFixedThreadPool創建一個固定數量線程的線程池。

27. 可變參數

public static void printNumbers(int... numbers) {
    for (int num : numbers) {
        System.out.println(num);
    }
}

public static void main(String[] args) {
    printNumbers(1, 2, 3, 4, 5);
}
講解

可變參數(varargs)允許傳遞不確定數量的參數給方法。用語法int... numbers定義變量參數,可以當作數組使用。

28. 枚舉

public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class Main {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        System.out.println("Today is " + today);
    }
}
講解

枚舉是一種特殊類,用於定義有限數量的常量。它顯式表達一個變量可選項列表,提升代碼可讀性和安全性。

29. 反射

import java.lang.reflect.Method;

public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        Class<?> cls = Class.forName("java.lang.String");
        Method[] methods = cls.getMethods();
        for (Method method : methods) {
            System.out.println("Method: " + method.getName());
        }
    }
}
講解

反射允許在運行時動態訪問類、方法和字段。此技術可用於工具開發、序列化框架和依賴注入等高級任務,並提供方法遍歷java.lang.String類。

30. 註解

@interface MyAnnotation {
    String value();
}

@MyAnnotation(value = "Example")
public class AnnotatedClass {
    // 該類使用了自定義註解
}
講解

註解為代碼提供元數據,廣泛應用於框架和庫中查找信息。自定義註解可用於文檔記錄和靜態檢查。

31. Singleton模式

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
講解

單例模式保證一個類只有一個實例,並提供一個全局訪問點。使用私有構造函數和靜態方法,下次調用getInstance()時返回已有實例。

32. Builder模式

public class Product {
    private final String name;
    private final double price;

    private Product(Builder builder) {
        this.name = builder.name;
        this.price = builder.price;
    }

    public static class Builder {
        private String name;
        private double price;

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

        public Builder setPrice(double price) {
            this.price = price;
            return this;
        }

        public Product build() {
            return new Product(this);
        }
    }
}

Product product = new Product.Builder()
    .setName("Example Product")
    .setPrice(29.99)
    .build();
講解

建造者模式允許構建複雜對象的過程與表示分離。此模式尤其適合對象具有多個可選參數的情況,通過鏈式調用提升代碼易讀性。

33. Lambda表達式

interface MathOperation {
    int operation(int a, int b);
}

MathOperation addition = (a, b) -> a + b;

System.out.println(addition.operation(5, 3)); // 應輸出8
講解

Lambda表達式是簡化的一種匿名內部類,提供了簡潔的語法來表示函數式接口(只有一個抽象方法的接口)的實現。

34. 方法引用

import java.util.function.Consumer;

public class MethodReference {
    public static void main(String[] args) {
        Consumer<String> printer = System.out::println;
        printer.accept("Hello, Java!");
    }
}
講解

方法引用是一種簡潔且易讀的Lambda表達式形式。使用::引用類方法或實例方法,如System.out::println

35. Stream API

import java.util.Arrays;
import java.util.List;

public class StreamExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
        names.stream()
             .filter(name -> name.startsWith("A"))
             .forEach(System.out::println);
    }
}
講解

Stream API支持以聲明式風格處理數據集合,簡化代碼,並支持集合操作如過濾、映射和歸約。

36. 正則表達式

import java.util.regex.Matcher;
import java.util.regex.Pattern;

Pattern pattern = Pattern.compile("a*b");
Matcher matcher = pattern.matcher("aaaaab");
boolean matchFound = matcher.matches();
System.out.println("Match Found: " + matchFound);
講解

正則表達式提供強大的模式匹配機制。PatternMatcher類是Java正則表達式API的核心,支持各種複雜字符串操作。

37. JUnit單元測試

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class SimpleTest {
    @Test
    public void testAddition() {
        assertEquals(5, 2 + 3);
    }
}
講解

JUnit是Java生態系統中常用的單元測試框架,使用簡單註解@Test來定義測試方法,並通過斷言檢查程序行為。

38. 序列化和反序列化

import java.io.*;

class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;

    Person(String name) {
        this.name = name;
    }
}

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
    Person person = new Person("Alice");
    oos.writeObject(person);
} catch (IOException e) {
    e.printStackTrace();
}

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.ser"))) {
    Person deserializedPerson = (Person) ois.readObject();
    System.out.println("Deserialized Name: " + deserializedPerson.name);
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}
講解

序列化可將對象轉換為字節流以便存儲或傳輸。反序列化則是將字節流恢復為對象。Serializable接口標記類支持這些過程。

39. 圖形用户界面(GUI)基礎

import javax.swing.*;
import java.awt.*;

public class SimpleGUI {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Simple GUI");
        JButton button = new JButton("Press me");

        button.addActionListener(e -> System.out.println("Button pressed!"));

        frame.setLayout(new FlowLayout());
        frame.add(button);
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
講解

Java的Swing庫用於創建圖形用户界面,需要創建JFrame作為窗口,添加JButton等組件,並添加事件監聽來處理用户交互。

40. 網絡編程

import java.net.*;
import java.io.*;

public class SimpleClient {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 1234);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
            out.println("Hello Server!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
講解

網絡編程支持通信程序之間的連接和數據交換。這裏程序創建一個簡單的TCP客户端,通過Socket連接發送數據。

41. JDBC數據庫連接

import java.sql.*;

public class DatabaseExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String user = "username";
        String password = "password";

        try (Connection conn = DriverManager.getConnection(url, user, password);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM mytable")) {
            while (rs.next()) {
                System.out.println(rs.getString("column_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
講解

JDBC是Java用於數據庫交互的API,執行查詢和更新SQL數據庫。連接數據庫後,通過Statement接口執行SQL語句操作。

42. 使用Optional類

import java.util.Optional;

public class OptionalExample {
    public static void main(String[] args) {
        Optional<String> optionalValue = Optional.of("Hello");
        optionalValue.ifPresent(System.out::println);

        String value = optionalValue.orElse("Default Value");
        System.out.println(value);
    }
}
講解

Optional是Java 8引入的一個容器類,用於避免null值引發的異常,提供安全獲取和操作潛在有無的值的方法。

43. 使用LocalDate和LocalDateTime

import java.time.LocalDate;
import java.time.LocalDateTime;

public class DateExample {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        LocalDateTime dateTime = LocalDateTime.now();

        System.out.println("Date: " + date);
        System.out.println("DateTime: " + dateTime);
    }
}
講解

LocalDateLocalDateTime是用於處理日期和時間的新API,提供更簡便和安全的方法來操作時間信息,而不再使用線程不安全的java.util.Date.

44. 在Java中使用正則進行匹配

import java.util.regex.Pattern;

public class RegexExample {
    public static void main(String[] args) {
        String text = "Java is fun!";
        Pattern pattern = Pattern.compile("Java");
        if (pattern.matcher(text).find()) {
            System.out.println("The text contains 'Java'");
        }
    }
}
講解

正則表達式是一種強有力的工具,用於在字符串中尋找符合條件的子串,PatternMatcher在Java中提供了正則表達式的完整支持。

45. 使用CompletableFuture進行異步編程

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("Async Task");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        future.join(); // Wait for the task to complete
    }
}
講解

CompletableFuture 是 Java 8 中引入的新類,用於異步編程,可以在非阻塞的方式下完成任務,提高程序的性能和響應能力。

46. Java中VCS的應用

Java中的版本控制系統(VCS)通常使用Git,在代碼示例中不直接涉及VCS的具體應用,而是強調良好使用版本控制策略的重要性,包括常見的分支管理(如Git Flow)、提交管理以及使用IDE集成VCS工具進行代碼變更跟蹤和歷史管理。

47. Java中實現Observer設計模式

import java.util.ArrayList;
import java.util.List;

interface Observer {
    void update(String message);
}

class Subject {
    private List<Observer> observers = new ArrayList<>();
    
    void addObserver(Observer o) {
        observers.add(o);
    }
    
    void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}

class ConcreteObserver implements Observer {
    private String name;
    
    ConcreteObserver(String name) {
        this.name = name;
    }

    public void update(String message) {
        System.out.println(name + " received: " + message);
    }
}

public class ObserverDemo {
    public static void main(String[] args) {
        Subject subject = new Subject();
        
        Observer observer1 = new ConcreteObserver("Observer 1");
        Observer observer2 = new ConcreteObserver("Observer 2");
        
        subject.addObserver(observer1);
        subject.addObserver(observer2);
        
        subject.notifyObservers("Hello, Observers!");
    }
}
講解

觀察者模式定義對象間的一對多依賴關係。當一個對象改變狀態時,所有依賴者都會收到通知並自動更新。適用於系統中多個對象間的這類通信需求。

48. 使用Spring Boot構建Web應用

Spring Boot是一個用於創建獨立、生產級Spring應用程序的框架,提供了約定優於配置理念,簡化了Spring應用的開發過程。以下是一個簡單的Spring Boot應用示例:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;

@SpringBootApplication
@RestController
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}
講解

@SpringBootApplication註解標記Spring Boot應用主類,該類需擁有main方法來啓動應用。@RestController@GetMapping用於定義RESTful Web服務端點。

49. 使用Hibernate進行持久化

Hibernate是Java中的一種持久化框架,簡化了數據庫訪問,並實現了輕量級的Object-Relational Mapping (ORM)。以下是一個基本示例:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    // Getters and setters
}

public class HibernateUtil {
    private static final SessionFactory sessionFactory = new Configuration()
        .configure("hibernate.cfg.xml")
        .buildSessionFactory();
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

public class HibernateExample {
    public static void main(String[] args) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            session.beginTransaction();

            User user = new User();
            user.setName("Alice");
            
            session.save(user);
            session.getTransaction().commit();
        }
    }
}
講解

Hibernate simplifies the task of interacting with a relational database by automatically handling the low-level details. Using annotations like @Entity, @Id, and @GeneratedValue, Hibernate can map Java objects to database tables.

50. 使用Mockito進行單元測試

Mockito是Java單元測試過程中常用的一個mocking框架,以下是一個示例:

import static org.mockito.Mockito.*;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

public class MockitoExample {
    @Mock
    MyDatabase databaseMock;
    
    @InjectMocks
    MyService service;
    
    @Test
    public void testQuery() {
        when(databaseMock.query(anyString())).thenReturn("some data");

        String result = service.queryDatabase("query string");
        
        assertEquals("some data", result);
        verify(databaseMock).query("query string");
    }
}
講解

Mockito通過創建、配置以及驗證mock對象簡化單元測試。@Mock標記的對象由Mockito的mocking機制自動生成,而@InjectMocks通過注入mock對象,實現對被測類的依賴管理。


以上是Java學習中常見的50個編程概念與代碼示例。在掌握這些基礎與高級技巧後,你將更具備駕馭Java項目開發的能力。不斷學習和實踐將提升你的編程技能和職業發展潛力。