JAVA注解和反射
一、注解
1.1注解入门
- Annotation是JDK5.0开始引入的新技术
- Annotation的作用:
- 不是程序本身,可以对程序做出解释。(这一点和注释(comment)没有什么区别)
- 可以被其他程序(比如:编译器)读取
- Annotation的格式
- 注解是以“@注释名”在代码中存在的,还可以添加一些参数值,例如:@SuppressWarnings(value="unchecked")
- Annotation在哪里使用
- 可以附加在package,class,method,field等上面,相当于给他们添加了额外的辅助信息,我们可以通过反射机制编程对这些元数据访问
package com.Annotation;
//什么是注解
public class TestAnnotation extends Object{
//注解
@Override
public String toString() {
return super.toString();
}
}
1.2内置注解
package com.Annotation;
//什么是注解
public class TestAnnotation extends Object{
//重写注解
@Override
public String toString() {
return super.toString();
}
//不推荐程序员使用,但是可以使用或有有更好的方式
@Deprecated
public boolean c(){
return true;
}
//镇压警告
@SuppressWarnings("all")
public void b(){
}
}
1.3自定义注解,元注解
package com.Annotation;
import java.lang.annotation.*;
//测试元注解
public class TestAnnotation02 {
@MyAnnotation
public void test(){
}
}
//定义一个注解
//Target表示我们注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention表示我们的注解在什么地方还有效
//runtime>class>sources
@Retention(value = RetentionPolicy.RUNTIME )
//Documented 表示是否将我们的注解生成在JAVADOC中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
package com.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class TestAnnotation03 {
//注解可以显式赋值,如果没有默认值,我们必须给注解复制
@MyAnnotation02(name = "石头",schools = {"沙子","水泥"})
public void test(){
}
//一个参数可以不用写参数名和等于号
@MyAnnotation3("房子")
public void test2(){
}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation02{
//注解的参数:参数类型+参数名
String name () default "";
int age() default 0;
int id() default -1 ;//如果默认值为-1,代表不存在
String[] schools();
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}
二、反射机制
2.1Java反射机制概述
2.2理解Class类并获取Class实例
package com.Refiection;
//什么叫反射
public class TestRefiection {
public static void main(String[] args) throws ClassNotFoundException {
//通过反射获取类的Class对象
Class c1= java.lang.Class.forName("com.Refiection.User");
System.out.println(c1);
Class c2= java.lang.Class.forName("com.Refiection.User");
Class c3= java.lang.Class.forName("com.Refiection.User");
Class c4= java.lang.Class.forName("com.Refiection.User");
//一个类在内存中只有一个Claas对象
//一个类被加载后,类的整个结构都会被封装在Class对象中
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
System.out.println(c4.hashCode());
System.out.println(c1.getClass());
}
}
//实体类:poj entity
class User{
private String name;
private int id;
private int age;
public User() {
}
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
package com.Refiection;
import java.lang.annotation.ElementType;
//所有类型的class
public class Test {
public static void main(String[] args) {
Class c1 = Object.class;//类
Class c2 = Comparable.class;//接口
Class c3 = String[].class;//一维数组
Class c4 = int[][].class;//二维数组
Class c5 = Override.class;//注解
Class c6 = ElementType.class;//枚举
Class c7 = Integer.class;//基本数据类型
Class c8 = void.class;//void
Class c9 = Class.class;//Class
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
System.out.println(c5);
System.out.println(c6);
System.out.println(c7);
System.out.println(c8);
System.out.println(c9);
//只要元素类型与维度一样,就是同一个class
int[] a = new int[10];
int[] b = new int[100];
System.out.println(a.getClass().hashCode());
System.out.println(b.getClass().hashCode());
}
}
2.3类的加载与ClassLoader
package com.Refiection;
public class Test02 {
public static void main(String[] args) {
A a = new A();
System.out.println(A.m);
/*
1.加载到内存,会产生一个类对应class对象
2.链接,链接结束后 m= 0
3.初始化
<clinit>(){
System.out.println("A类静态代码块初始化");
int m=300;
int m= 100;
}
*/
}
}
class A{
static {
System.out.println("A类静态代码块初始化");
int m=300;
}
/*
* m=300;
* m=100;
* */
static int m= 100;
public A(){
System.out.println("A类的无参构造初始化");
}
}
测试类的初始化
主动引用,会有初始化
package com.Refiection;
//测试类什么时候会初始化
public class Test03 {
static {
System.out.println("main被加载");
}
public static void main(String[] args) throws ClassNotFoundException {
//1.主动引用
Son son = new Son();
//反射也会产生引用
// System.out.println(Class.forName("com.Refiection.Son"));
}
}
class Father{
static int b = 2;
static {
System.out.println("父类被加载");
}
}
class Son extends Father{
static {
System.out.println("子类被加载");
m = 300;
}
static int m = 100;
static final int N=1;
}
被动引用:不会有初始化
package com.Refiection;
//测试类什么时候会初始化
public class Test03 {
static {
System.out.println("main被加载");
}
public static void main(String[] args) throws ClassNotFoundException {
//不会产生主动引用的方法
// System.out.println(Son.b);
// Son[] array = new Son[5];
System.out.println(Son.M);
}
}
class Father{
static int b = 2;
static {
System.out.println("父类被加载");
}
}
class Son extends Father{
static {
System.out.println("子类被加载");
m = 300;
}
static int m = 100;
static final int M=1;
}
类加载器
package com.Refiection;
public class Test04 {
public static void main(String[] args) throws ClassNotFoundException {
//获取系统类的加载器
ClassLoader platformClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(platformClassLoader);
//获取系统类加载器的父类加载器-->扩展类加载器
ClassLoader parent = platformClassLoader.getParent();
System.out.println(parent);
//获取扩展类加载器的父类加载器-->更加载器(c/c++)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
//测试当前类是哪个加载器加载的
ClassLoader classLoader = Class.forName("com.Refiection.Test04").getClassLoader();
System.out.println(classLoader);
//测试JDK内置的类是谁加载的
classLoader = Class.forName("java.lang.Object").getClassLoader();
System.out.println(classLoader);
//如何获得系统加载器可以加载的路径
System.out.println(System.getProperty("java.class.path"));
/*C:\Users\XIANG\Desktop\JavaCode\out\production\java-code;
C:\Users\XIANG\Desktop\JavaCode\src\lib\commons-io-2.6.jar
*/
//双亲委派机制
//java.lang.String-->
}
}
2.4获取运行时类的完整结构
package com.Refiection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Test05 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
// Class c1 = Class.forName("com.Refiection.User");
User user =new User();
Class c1 = user.getClass();
//获得类的名字
System.out.println(c1.getName());//获得包名和类名
System.out.println(c1.getSimpleName());//获得类名
//获得类的属性
System.out.println("==============");
Field[] fields = c1.getFields();
fields=c1.getDeclaredFields();
for(Field field :fields){
System.out.println(field);
}
//获得指定属性的值
Field name = c1.getDeclaredField("name");
System.out.println(name);
//获得类的方法
System.out.println("==================");
//获得本类及其父类的全部public方法
Method[] methods = c1.getMethods();
for(Method method :methods){
System.out.println("正常的"+method);
}
//获得本类的全部方法包括私有类
methods = c1.getDeclaredMethods();
for(Method method :methods){
System.out.println("getDeclaredMethods:"+method);
}
//获得指定方法
//重载
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//获得本类及其父类的全部public构造器
System.out.println("==================");
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
//获得本类的全部构造器包括私有
constructors = c1.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println("#"+constructor);
}
//获得指定的构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println(declaredConstructor);
}
}
newInstance
package com.Refiection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test06 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
//获得class对象
Class c1 = Class.forName("com.Refiection.U");
//构造一个对象
U user = (U) c1.getDeclaredConstructor().newInstance();//本质调用了类的无参构造器
System.out.println(user);
//通过构造器创建对象
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
U user2 =(U)declaredConstructor.newInstance("反射",1,2);
System.out.println(user2);
//通过反射调用普通方法
U user3 =(U) c1.getDeclaredConstructor().newInstance();
//通过反射获取一个方法
Method setName = c1.getDeclaredMethod("setName",String.class);
//invoke:激活的意思
//(对象,“方法的值”)
setName.invoke(user3,"反射");
System.out.println(user3.getName());
//通过反射操作属性
System.out.println("================================");
U user4 = (U) c1.getDeclaredConstructor().newInstance();
Field name = c1.getDeclaredField("name");
//不能直接操作私有属性,我们需要关闭程序的安全检查,属性或者方法的setAccessible(true);
name.setAccessible(true);
name.set(user4,"反射");
System.out.println(user4.getName());
}
}
class U{
private String name;
private int id;
private int age;
public U() {
}
public U(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
分析性能问题
package com.Refiection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//分析性能问题
public class Test07 {
//普通方式调用
public static void test01(){
UTest user= new UTest();
long startTime = System.currentTimeMillis();
// System.out.println(user.getName());
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long endTime = System.currentTimeMillis();
System.out.println("普通方式执行10亿次:"+(endTime-startTime)+"ms");
}
//反射方式调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
UTest user= new UTest();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式调用执行10亿次:"+(endTime-startTime)+"ms");
}
//反射方式调用,关闭检测
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
UTest user= new UTest();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName", null);
getName.setAccessible(true);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user,null);
}
long endTime = System.currentTimeMillis();
System.out.println("反射方式调用,关闭检测执行10亿次:"+(endTime-startTime)+"ms");
}
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
test01();
test02();
test03();
}
}
class UTest{
private String name;
private int id;
private int age;
public UTest() {
}
public UTest(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
2.5调用运行时类的指定结构
获取泛型信息
package com.Refiection;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
//通过反射获取泛型
public class Test08 {
public void test01(Map<String,User> map, List<User>list){
System.out.println("test01");
}
public Map<String,User> test02(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = Test08.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("###:"+genericParameterType);
if(genericParameterType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
method = Test08.class.getMethod("test02");
Type genericReturnType = method.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArgyments = ((ParameterizedType)genericReturnType).getActualTypeArguments();
for (Type actualTypeArgyment : actualTypeArgyments) {
System.out.println("--->"+actualTypeArgyment);
}
}
}
}
//实体类:poj entity
class User{
private String name;
private int id;
private int age;
public User() {
}
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", id=" + id +
", age=" + age +
'}';
}
}
反射操作注解
- getAnnotations
- getAnnotation
package com.Refiection;
import java.lang.annotation.*;
import java.lang.reflect.Method;
//联系发射操作注解
public class Test09 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.Refiection.Student2");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解的value的值
Table table= (Table)c1.getAnnotation(Table.class);
String value = table.value();
System.out.println(value);
//获得指定的注解
java.lang.reflect.Field name = c1.getDeclaredField("name");
Field annotation = name.getAnnotation(Field.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Table("db_student")
class Student2{
@Field(columnName = "db_id",type = "int",length = 10)
private int id;
@Field(columnName = "db_age",type = "int",length = 10)
private int age;
@Field(columnName = "db_name",type = "varchar",length = 10)
private String name;
public Student2() {
}
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field{
String columnName();
String type();
int length();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?