1. OOP(面向对象编程)

OOP(Object-Oriented Programming)是一种编程范式,它将数据和操作数据的方法封装在对象中,通过类的定义来创建对象,实现代码的模块化和复用。

核心特性

  • 封装:隐藏对象内部实现细节,只暴露必要接口
  • 继承:允许创建新类继承现有类的属性和方法
  • 多态:同一操作作用于不同对象可产生不同结果
  • 抽象:提取共同特征形成抽象类或接口

示例

// 封装
public class User {
    private String name;  // 私有属性
    
    // 公共方法
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
}

// 继承与多态
public class Animal {
    public void makeSound() {
        System.out.println("Animal sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {  // 多态实现
        System.out.println("Woof");
    }
}

2. 反射(Reflection)

反射是指程序在运行时可以访问、检测和修改自身状态或行为的能力。通过反射,我们可以在编译时未知的情况下操作类或对象。

主要用途

  • 动态创建类的实例
  • 访问和修改类的私有成员
  • 动态调用方法
  • 处理注解

Java 反射示例

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

public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        // 获取类对象
        Class<?> clazz = User.class;
        
        // 动态创建实例
        Object user = clazz.getDeclaredConstructor().newInstance();
        
        // 获取并调用方法
        Method setNameMethod = clazz.getMethod("setName", String.class);
        setNameMethod.invoke(user, "John Doe");
        
        // 访问私有字段
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);  // 突破访问限制
        String name = (String) nameField.get(user);
        System.out.println("Name: " + name);
    }
}
    

应用场景:框架开发(如 Spring)、ORM 工具(如 MyBatis)、序列化与反序列化等。

3. 动态代理(Dynamic Proxy)

动态代理是一种在运行时创建代理对象的技术,允许在不修改原始类代码的情况下,对方法调用进行拦截和增强。

主要用途

  • 实现 AOP(面向切面编程)
  • 远程调用(RPC)
  • 权限控制
  • 日志记录

Java 动态代理示例

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 目标接口
interface UserService {
    void addUser(String name);
}

// 目标实现类
class UserServiceImpl implements UserService {
    @Override
    public void addUser(String name) {
        System.out.println("Adding user: " + name);
    }
}

// 代理处理器
class LoggingHandler implements InvocationHandler {
    private Object target;
    
    public LoggingHandler(Object target) {
        this.target = target;
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 前置增强
        System.out.println("Before invoking " + method.getName());
        
        // 调用目标方法
        Object result = method.invoke(target, args);
        
        // 后置增强
        System.out.println("After invoking " + method.getName());
        
        return result;
    }
}

public class DynamicProxyDemo {
    public static void main(String[] args) {
        // 创建目标对象
        UserService userService = new UserServiceImpl();
        
        // 创建代理对象
        UserService proxy = (UserService) Proxy.newProxyInstance(
            UserService.class.getClassLoader(),
            new Class[] { UserService.class },
            new LoggingHandler(userService)
        );
        
        // 通过代理对象调用方法
        proxy.addUser("John Doe");
    }
}
    

4. IOC(控制反转)

IOC(Inversion of Control)是一种设计原则,它将对象的创建和依赖管理的控制权从应用程序代码转移到容器。

传统方式 vs IOC 方式

  • 传统:对象自己创建和管理依赖(A a = new A();
  • IOC:容器创建对象并注入依赖,对象被动接收依赖

核心思想

  • 解耦:降低组件间的依赖关系
  • 复用:组件更易于重用
  • 测试:便于进行单元测试
  • 维护:提高代码可维护性

5. IOC 容器

IOC 容器是实现 IOC 原则的框架组件,负责对象的创建、配置和管理。

主要功能

  • 对象的实例化
  • 依赖注入(DI)
  • 对象生命周期管理
  • 配置管理

Spring IOC 容器示例

// 服务类
public class UserService {
    private UserRepository userRepository;
    
    // 构造函数注入
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    public void createUser(String name) {
        userRepository.save(name);
    }
}

// 依赖类
public class UserRepository {
    public void save(String name) {
        System.out.println("Saving user: " + name);
    }
}

// 配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    @Bean
    public UserRepository userRepository() {
        return new UserRepository();
    }
    
    @Bean
    public UserService userService() {
        // 容器注入依赖
        return new UserService(userRepository());
    }
}

// 应用程序
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringIocDemo {
    public static void main(String[] args) {
        // 初始化IOC容器
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        
        // 从容器获取对象
        UserService userService = context.getBean(UserService.class);
        
        // 使用对象
        userService.createUser("John Doe");
    }
}
    

6. AOP(面向切面编程)

AOP(Aspect-Oriented Programming)是一种编程范式,它通过将横切关注点(如日志、事务、安全)从业务逻辑中分离出来,提高代码的模块化程度。

核心概念

  • 切面(Aspect):横切关注点的模块化
  • 连接点(Join Point):程序执行过程中的点
  • 通知(Advice):切面在特定连接点执行的动作
  • 切点(Pointcut):匹配连接点的表达式
  • 织入(Weaving):将切面应用到目标对象的过程

Spring AOP 示例

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

// 启用AOP支持
@Configuration
@EnableAspectJAutoProxy
public class AopConfig {
    
    // 定义切面
    @Aspect
    public static class LoggingAspect {
        
        // 定义切点:匹配UserService的所有方法
        @Pointcut("execution(* UserService.*(..))")
        public void userServiceMethods() {}
        
        // 前置通知
        @Before("userServiceMethods()")
        public void beforeMethod() {
            System.out.println("Before method execution");
        }
        
        // 后置通知
        @After("userServiceMethods()")
        public void afterMethod() {
            System.out.println("After method execution");
        }
    }
}

// 使用AOP的服务类
public class UserService {
    public void addUser(String name) {
        System.out.println("Adding user: " + name);
    }
    
    public void deleteUser(String name) {
        System.out.println("Deleting user: " + name);
    }
}

// 应用程序
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringAopDemo {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        
        // 从容器获取代理对象
        UserService userService = context.getBean(UserService.class);
        
        // 方法调用会被AOP增强
        userService.addUser("John Doe");
        userService.deleteUser("John Doe");
    }
}
    

概念关系总结

  1. OOP 是基础编程范式,其他概念大多基于 OOP 构建
  2. 反射 是实现动态代理的基础技术
  3. 动态代理 是实现 AOP 的核心技术
  4. IOC 容器 负责对象管理和依赖注入
  5. AOP 通常与 IOC 容器结合使用,实现横切关注点的分离

这些概念共同构成了现代 Java 框架(如 Spring)的基础,理解它们对于掌握企业级应用开发至关重要。

Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐