Java泛型(Generics):
Java泛型是JDK 5引入的一个新特性,它允许在定义类、接口和方法时使用类型参数,这个类型参数将在实际使用时(例如,创建对象或调用方法时)被具体的类型替换。泛型的主要目标是提高Java程序的类型安全。
以下是一个使用泛型的简单示例:
public class Box<T> {
private T t; // T stands for "Type"
public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
Box<String> stringBox = new Box<String>();
integerBox.set(new Integer(10));
stringBox.set(new String("Hello World"));
System.out.printf("Integer Value :%d\n\n", integerBox.get());
System.out.printf("String Value :%s\n", stringBox.get());
}
}
在上面的代码中,Box
是一个泛型类,它使用一个类型参数T
。在main
方法中,我们创建了两个不同类型的Box
:一个用于Integer
,另一个用于String
。这就是泛型的用途:它允许我们编写可以处理各种数据类型的代码,同时保持类型安全。
Java注解(Annotations):
Java注解是从JDK 5开始引入的,它提供了一种元程序设计(meta-programming)的方法,允许在代码中添加一些元信息,这些元信息可以在编译时或运行时被处理,以实现某些功能。注解的语法使用@interface
关键字,它的形式跟接口很类似。
以下是一个使用注解的简单示例:
import java.lang.annotation.*;
// 定义一个注解
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value() default "default value";
}
// 使用注解
@MyAnnotation(value="Hello Annotation")
public class Test {
public static void main(String[] args) {
// 获取注解信息
if (Test.class.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation myAnnotation = Test.class.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.value());
}
}
}
在上述代码中,我们首先定义了一个名为MyAnnotation
的注解,然后在Test
类上使用了该注解,并在main
方法中获取并打印了注解的值。这就是注解的基本用法:它允许我们在代码中添加一些额外的信息,然后在运行时读取这些信息。注解在很多框架(如Spring)中都有广泛的应用。