新三国小镇
55.33 MB · 2025-12-17
泛型是 JDK 5 引入的特性,本质是参数化类型,允许在定义类、接口和方法时使用类型参数,在使用时再指定具体类型。
public class Box<T> {
private T value;
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
// 使用泛型类
Box<String> stringBox = new Box<>();
stringBox.setValue("Hello"); // 只能设置String类型
String result = stringBox.getValue(); // 无需类型转换
public interface List<T> {
void add(T element);
T get(int index);
}
public <T> T getFirstElement(List<T> list) {
if (list != null && !list.isEmpty()) {
return list.get(0);
}
return null;
}
<?>:表示任意类型<? extends T>:表示 T 类型或其子类<? super T>:表示 T 类型或其父类泛型信息只存在于编译阶段,在编译后生成的字节码中,泛型相关信息会被擦除:
T、?)会被替换为 ObjectT extends Person)会被替换为上界类型反射是 Java 提供的一种能够在运行时检查、获取和修改类的结构(属性、方法、构造器等)的机制。
// 1. 获取Class对象
Class<?> clazz = Class.forName("com.example.User");
// 或
Class<?> clazz = User.class;
// 或
Class<?> clazz = new User().getClass();
// 2. 创建对象
Object instance = clazz.getDeclaredConstructor().newInstance();
// 3. 获取方法并调用
Method method = clazz.getMethod("setName", String.class);
method.invoke(instance, "张三");
// 4. 获取属性并修改
Field field = clazz.getDeclaredField("age");
field.setAccessible(true); // 设置可访问私有属性
field.set(instance, 25);
注解是 JDK 5 引入的一种特殊标记,可以附加在类、方法、变量等元素上,用于为这些元素提供元数据信息。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default "";
int count() default 0;
}
// 使用自定义注解
public class Test {
@MyAnnotation(value = "测试", count = 3)
public void testMethod() {
// 方法体
}
}
通过反射获取和处理注解信息:
public void processAnnotations(Class<?> clazz) {
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value();
int count = annotation.count();
// 处理注解信息
}
}
}
Java 线程的生命周期包括七个状态:
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程执行");
}
}
MyThread thread = new MyThread();
thread.start();
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程执行");
}
}
Thread thread = new Thread(new MyRunnable());
thread.start();
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "线程执行结果";
}
}
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
String result = futureTask.get(); // 获取线程执行结果
// 同步方法
public synchronized void method() {
// 同步代码块
}
// 同步代码块
public void method() {
synchronized (this) {
// 同步代码
}
}
Lock lock = new ReentrantLock();
try {
lock.lock();
// 同步代码
} finally {
lock.unlock();
}
// NIO 使用示例
try (FileChannel channel = new FileInputStream("file.txt").getChannel()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
while (bytesRead != -1) {
buffer.flip(); // 切换到读模式
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear(); // 切换到写模式
bytesRead = channel.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
// 无参数无返回值
() -> System.out.println("Hello")
// 有参数无返回值
(String s) -> System.out.println(s)
// 有参数有返回值
(a, b) -> a + b
只有一个抽象方法的接口,可以使用 @FunctionalInterface 注解标记。
List<String> list = Arrays.asList("apple", "banana", "orange", "pear");
list.stream()
.filter(s -> s.length() > 5)
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
Optional<String> optional = Optional.ofNullable(value);
String result = optional.orElse("默认值");
// 静态方法引用
list.forEach(System.out::println);
// 实例方法引用
list.forEach(String::toUpperCase);
// 构造器引用
Stream.of("a", "b").map(StringBuilder::new).forEach(System.out::println);
Java 高级特性是 Java 语言强大功能的体现,掌握这些特性对于开发复杂、高效的应用程序至关重要:
通过深入学习和实践这些高级特性,可以显著提升 Java 编程能力和代码质量。