
Java 17作为长期支持版本(LTS),引入了多项重要特性:
sealed关键字限制类的继承,增强类型安全性。例如:public sealed class Shape
permits Circle, Rectangle, Triangle {
// 共同属性和方法
}instanceof和switch表达式,简化代码:if (obj instanceof String s) {
System.out.println(s.length()); // 直接使用s
}"""定义多行字符串,避免转义:String html = """
<html>
<body>
<p>Hello, World!</p>
</body>
</html>
""";findFirst()、findAny()等短路操作:Optional<Integer> firstEven = list.stream()
.filter(n -> n % 2 == 0)
.findFirst(); // 找到第一个偶数即终止parallelStream():long sum = list.parallelStream()
.mapToLong(MyClass::getValue)
.sum();IntStream、LongStream等原始类型流:IntStream.range(1, 100)
.filter(i -> i % 2 == 0)
.sum(); // 避免Integer装箱Record类自动生成构造器、equals()、hashCode()和toString(),例如:
public record User(String name, int age) {
// 自动生成所有字段的getter和构造器
}
// 使用示例
User user = new User("Alice", 30);
System.out.println(user.name()); // 访问字段使用枚举实现单例,自动保证线程安全和反序列化安全:
public enum Singleton {
INSTANCE;
public void doSomething() {
System.out.println("Singleton action");
}
}
// 使用示例
Singleton.INSTANCE.doSomething();处理多个异步任务的组合:
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
return "Result1";
});
CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
return "Result2";
});
CompletableFuture<Void> allTasks = CompletableFuture.allOf(task1, task2);
allTasks.thenRun(() -> {
try {
System.out.println(task1.get());
System.out.println(task2.get());
} catch (Exception e) {
e.printStackTrace();
}
});通过构造函数指定公平策略:
private final Lock fairLock = new ReentrantLock(true); // 公平锁
public void doWork() {
fairLock.lock();
try {
// 业务逻辑
} finally {
fairLock.unlock();
}
}快速创建不可变集合:
List<String> immutableList = List.of("a", "b", "c");
Set<Integer> immutableSet = Set.of(1, 2, 3);
Map<String, Integer> immutableMap = Map.of("one", 1, "two", 2);按条件分组并统计:
Map<String, List<Person>> peopleByCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity));
Map<String, Long> countByCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity, Collectors.counting()));Path filePath = Path.of("data.txt");
// 写入文件
Files.writeString(filePath, "Hello, World!", StandardOpenOption.CREATE);
// 读取文件
String content = Files.readString(filePath);
// 遍历目录
try (Stream<Path> paths = Files.walk(Path.of("."))) {
paths.filter(Files::isRegularFile)
.forEach(System.out::println);
}// 服务器端
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.bind(new InetSocketAddress(8080));
serverChannel.configureBlocking(false);
Selector selector = Selector.open();
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = keys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if (key.isAcceptable()) {
// 处理连接
} else if (key.isReadable()) {
// 处理读取
}
keyIterator.remove();
}
}public interface Shape {
void draw();
}
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Circle");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing Rectangle");
}
}
public class ShapeFactory {
public static Shape createShape(String type) {
return switch (type.toLowerCase()) {
case "circle" -> new Circle();
case "rectangle" -> new Rectangle();
default -> throw new IllegalArgumentException("Unknown shape type: " + type);
};
}
}import java.util.ArrayList;
import java.util.List;
public class NewsPublisher {
private final List<Observer> observers = new ArrayList<>();
private String news;
public void addObserver(Observer observer) {
observers.add(observer);
}
public void removeObserver(Observer observer) {
observers.remove(observer);
}
public void setNews(String news) {
this.news = news;
notifyObservers();
}
private void notifyObservers() {
observers.forEach(o -> o.update(news));
}
}
public interface Observer {
void update(String news);
}
public class NewsReader implements Observer {
private final String name;
public NewsReader(String name) {
this.name = name;
}
@Override
public void update(String news) {
System.out.println(name + " received news: " + news);
}
}@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
private int age;
// getters/setters
}
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}
// 使用示例
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getUsersByName(String name) {
return userRepository.findByName(name);
}
}Pageable接口实现分页Pageable pageable = PageRequest.of(0, 10, Sort.by("name").ascending());
Page<User> users = userRepository.findAll(pageable);@EntityGraph或JOIN FETCH优化关联查询@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.saveUser(user);
}
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}// 服务注册中心(Eureka Server)
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
// 服务提供者
@SpringBootApplication
@EnableEurekaClient
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
}
// 服务消费者(使用Feign)
@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
@FeignClient(name = "product-service")
public interface ProductClient {
@GetMapping("/products/{id}")
Product getProduct(@PathVariable("id") Long id);
}// 使用Resilience4j
@Service
public class ProductService {
@CircuitBreaker(name = "productService", fallbackMethod = "getProductFallback")
public Product getProduct(Long id) {
// 调用远程服务
}
public Product getProductFallback(Long id, Throwable t) {
// 降级逻辑
return new Product(id, "Fallback Product", 0.0);
}
}-Xms和-Xmximport static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class CalculatorServiceTest {
@Test
void testAdd() {
CalculatorService calculator = new CalculatorService();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
@Test
void testWithMock() {
Calculator calculator = mock(Calculator.class);
when(calculator.add(2, 3)).thenReturn(5);
CalculatorService service = new CalculatorService(calculator);
int result = service.addNumbers(2, 3);
assertEquals(5, result);
verify(calculator).add(2, 3);
}
}# GitHub Actions示例
name: Java CI
on:
push:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: Build with Maven
run: mvn clean test编写Dockerfile:
FROM openjdk:17-jdk-slim
WORKDIR /app
COPY target/myapp.jar /app/
EXPOSE 8080
CMD ["java", "-jar", "myapp.jar"]构建镜像:docker build -t myapp:1.0 .
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: myapp-deployment
spec:
replicas: 3
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:1.0
ports:
- containerPort: 8080
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: myapp-service
spec:
type: LoadBalancer
ports:
- port: 80
targetPort: 8080
selector:
app: myapppublic class VirtualThreadsDemo {
public static void main(String[] args) throws InterruptedException {
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
try (executor) {
IntStream.range(0, 10000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
});
});
}
}
}public class StructuredConcurrencyDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> task1 = scope.fork(() -> fetchUser());
Future<Integer> task2 = scope.fork(() -> fetchOrderCount());
scope.join(); // 等待所有任务完成
scope.throwIfFailed(); // 如果有任务失败,抛出异常
// 处理结果
String user = task1.resultNow();
int orderCount = task2.resultNow();
System.out.println(user + ": " + orderCount);
}
}
}通过本文的学习,你应该对Java面试中的核心知识点有了全面的理解。记住,理解原理比死记硬背更重要,多动手实践才能真正掌握这些技术。祝你面试成功!
以上内容结合了Java最新特性和实际应用场景,涵盖了从基础到高级的多个方面。每个部分都包含了理论解释和代码示例,帮助你更好地理解和掌握这些技术。
Java 2025 新特性,企业级项目,多场景应用,代码示例,Java 编程,性能优化,安全增强,云原生云原生,微服务架构,分布式系统,模式匹配,虚拟线程,值对象,抗量子加密,结构化并发
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。