可以通过以下的方式使用Java注解获取用户信息:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface UserInfo {
String name();
int age();
String email();
}
@UserInfo(name = "John Doe", age = 25, email = "johndoe@example.com")
public class Main {
public static void main(String[] args) {
Class<Main> clazz = Main.class;
UserInfo annotation = clazz.getAnnotation(UserInfo.class);
if (annotation != null) {
System.out.println("Name: " + annotation.name());
System.out.println("Age: " + annotation.age());
System.out.println("Email: " + annotation.email());
}
}
}
在上面的例子中,我们定义了一个UserInfo
注解,用于获取用户信息。注解中定义了三个元素:name
、age
、email
,用于表示用户的名字、年龄和邮箱。
在Main
类中,我们使用@UserInfo
注解来注释该类,并在main
方法中通过clazz.getAnnotation(UserInfo.class)
来获取注解的实例。然后我们可以使用注解的实例来获取用户的信息。
运行程序,输出如下:
Name: John Doe
Age: 25
Email: johndoe@example.com