注解
1.注解
注解是给程序看的,能被程序识别
在 Java 中,注解(Annotation)是一种元数据(metadata)形式,可以在类、方法、变量、参数等程序元素前添加以提供额外信息。注解提供了一种在源代码中嵌入元数据的方式,使得程序的结构、行为或其他方面可以被其他程序或工具读取和处理。
2.内置注解
内置注解示例:
1. `@Override`:用于标记方法覆盖父类中的方法。
2. `@Deprecated`:用于标记已过时的方法或类。
3. `@SuppressWarnings`:用于抑制编译器警告。
4. `@FunctionalInterface`:用于标记函数式接口。
3.元注解
在java中,元注解是能够注解其他注解的注解
常用的元注解:
1. @Retention:指定注解的保留策略,即注解在什么级别可用,有三个取值:
RetentionPolicy.RUNTIME:注解会被保留在编译后的字节码文件中,并在运行时可通过反射获取。
CLASS>SOURCE>RUNTIME
2. @Target:指定注解可以应用的程序元素类型,有多个取值,如`ElementType.METHOD、ElementType.FIELD等。
3. @Documented:指定注解是否会被包含在 Java 文档中。
4. @Inherited:指定注解是否会被子类继承。
5. @Repeatable:指定注解是否可以重复应用于同一程序元素。
4.自定义注解
自定义注解用@interface定义可以设置参数类型和参数默认值
@interface 注解名{
参数类型 参数默认值;}
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.METHOD) // 注解只能用于方法
public @interface MyAnnotation {
String value() default ""; // 注解的值,默认为空字符串
int number() default 0; // 另一个注解的值,默认为0
}
public class MyClass {
@MyAnnotation(value = "Hello, world!", number = 42)
public void myMethod() {
// ...
}
}
反射
1.反射概述
静态语言:java,c,c++
动态语言:go,python,js
动态语言运行时可以改变其结构,java是静态语言,但被称为准动态语言的原因就是因为强大的反射机制。
传统方式:1.引入包类名称 2.通过new实列化 3.取得实列化对象
反射方式:1.实列化对象 2.getclass方法 3.得到包类名称
2.获得反射对象
package com.liuy.pojo;
public class test {
public static void main(String[] args) throws ClassNotFoundException {
//通过反射获取Class对象
Class c1 = Class.forName("com.liuy.pojo.User");
System.out.println(c1);
Class c2 = Class.forName("com.liuy.pojo.User");
Class c3 = Class.forName("com.liuy.pojo.User");
Class c4 = Class.forName("com.liuy.pojo.User");
//一个类在内存中只有一个Class对象
//一个类被加载后,整个类的结构都会被封装在Class对象
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
System.out.println(c4.hashCode());
}
}
//实体类
class User {
private String name;
private int id;
public User() {
}
public User(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public voi