一、注解
1.1 注解入门
1.2 内置注解
1.3 元注解
枚举类
package com.annotation;
import java.lang.annotation.*;
// 测试元注解
public class Demo01{
@MyAnnotation
public static void test(){
}
}
// 定义一个元注解
//Target表示注解可以在哪些地方使用
@Target(value = {ElementType.METHOD,ElementType.TYPE})
// Retention表示注解在什么状态下有效
// runtime>class>source,rutime时才可被反射
@Retention(RetentionPolicy.RUNTIME)
@Documented //表示将注解生成在javadoc中
@Inherited // 表示子类可继承父类的注解
@interface MyAnnotation{
}
1.4 自定义注解
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 Demo02 {
// 如果没有默认值,则必须赋值
@MyAnnotation2(name="abv")
public void test(){
}
// 只有一个参数且参数名为value则可以省略参数名
@MyAnnotation3("abv")
public void test2(){
}
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
// 注解的参数:参数类型+参数名();
String name();
int age() default 1;//有默认值则使用时可以不传该参数
String[] address() default {"中国","浙江","杭州"};
}
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
// 只有一个参数时参数名建议用value;
String value();
}
二、反射
2.1 反射机制概述
package com.reflection;
public class Demo01 {
public static void main(String[] args) {
try {
// 通过反射获取类的对象
Class cls = Class.forName("com.reflection.User");
Class cls2 = Class.forName("com.reflection.User");
Class cls3 = Class.forName("com.reflection.User");
System.out.println(cls); //class com.reflection.User
// 一个类在内存中只有一个Class对象
// 一个类加载后,类的整个结构都会被封装在Class对象上
System.out.println(cls.hashCode());//1163157884
System.out.println(cls2.hashCode());//1163157884
System.out.println(cls3.hashCode());//1163157884
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
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 +
'}';
}
}
2.2 理解class类并获取class实例
获取Class实例的几种方式
哪些类型有Class对象?
package com.reflection;
import java.lang.annotation.ElementType;
public class Demo02 {
public static void main(String[] args) {
Class<Object> c1 = Object.class; // 类
Class<Runnable> c2 = Runnable.class;// 接口
Class<Override> c3 = Override.class;// 注解
Class<String[]> c4 = String[].class; // 一维数组
Class<String[][]> c5 = String[][].class; // 二维数组
Class<ElementType> c6 = ElementType.class; // 枚举
Class<Integer> c7 = int.class; // 基础数据类型
Class<Integer> c8 = Integer.class; // 包装类
Class<Class> c9 = Class.class; // Class类
Class<Void> c10 = void.class; // void
System.out.println(c1); //class java.lang.Object
System.out.println(c2); //interface java.lang.Runnable
System.out.println(c3); //interface java.lang.Override
System.out.println(c4); //class [Ljava.lang.String;
System.out.println(c5); //class [[Ljava.lang.String;
System.out.println(c6); //class java.lang.annotation.ElementType
System.out.println(c7); //int
System.out.println(c8); //class java.lang.Integer
System.out.println(c9); //class java.lang.Class
System.out.println(c10); //void
}
}
2.3 类的加载与classLoader
类的加载过程
package com.reflection;
public class Demo05 {
static {
System.out.println("Main类被加载");
}
public static void main(String[] args) throws ClassNotFoundException {
// 1主动引用
// Son son = new Son();
// 2反射也会产生主动引用
// Class.forName("com.reflection.Son");
// 不会产生引用的方法
// System.out.println(Son.b);Son类不会加载
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.reflection;
public class Demo06 {
public static void main(String[] args) throws ClassNotFoundException {
//获取系统类加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);//sun.misc.Launcher$AppClassLoader@18b4aac2
//获取系统类加载器的父类加载器====>扩展类加载器
ClassLoader parent = systemClassLoader.getParent(); //sun.misc.Launcher$ExtClassLoader@4554617c
System.out.println(parent);
//获取扩展类加载器的父类加载器====>引导类加载器(C++编写,无法直接获取)
ClassLoader root = parent.getParent();
System.out.println(root); // null
//测试当前类时哪个加载器加载的
ClassLoader classLoader = Class.forName("com.reflection.Person").getClassLoader();
System.out.println(classLoader); // sun.misc.Launcher$AppClassLoader@18b4aac2
ClassLoader classLoader2 = Class.forName("java.lang.String").getClassLoader();
System.out.println(classLoader2);// null
//如何获得系统类加载器可以加载的路径
/*C:\Program Files\Java\jdk1.8.0_144\jre\lib\charsets.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\deploy.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\access-bridge-64.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\cldrdata.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\dnsns.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\jaccess.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\jfxrt.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\localedata.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\nashorn.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\sunec.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\sunjce_provider.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\sunmscapi.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\sunpkcs11.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\ext\zipfs.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\javaws.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\jce.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\jfr.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\jfxswt.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\jsse.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\management-agent.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\plugin.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\resources.jar;
C:\Program Files\Java\jdk1.8.0_144\jre\lib\rt.jar;
D:\java_leaning\JavaSE\out\production\basic;
D:\software\IntelliJ IDEA Community Edition 2022.1\lib\idea_rt.jar*/
System.out.println(System.getProperty("java.class.path"));
}
}
2.4 获取运行时类的完整结构
package com.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
// 获得类的信息(Class类的方法)
public class Demo07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.reflection.User");
/*User user = new User();
c1 = user.getClass();*/
//获得类的名字
System.out.println(c1.getName()); //com.reflection.User
System.out.println(c1.getSimpleName());//User
//获得类的属性
System.out.println("===========================");
Field[] fields = c1.getFields(); //只能获取到public属性
for (Field field : fields) {
System.out.println(field);
}
System.out.println("===========================");
Field[] declaredFields = c1.getDeclaredFields();//获取所有属性
for (Field declaredField : declaredFields) {
System.out.println(declaredField); //private java.lang.String com.reflection.User.name...
}
System.out.println(c1.getDeclaredField("name")); //获取指定名称属性
//获取类的方法
System.out.println("===========================");
for (Method method : c1.getMethods()) {//获得本类及其父类的所有public方法
System.out.println(method);
}
System.out.println("===========================");
for (Method method : c1.getDeclaredMethods()) {//获得本类所有方法
System.out.println(method);
}
System.out.println("===========================");
System.out.println(c1.getMethod("getName",null)); //public java.lang.String com.reflection.User.getName()
System.out.println(c1.getMethod("setName",String.class));//public void com.reflection.User.setName(java.lang.String)
//获取类的构造器
System.out.println("===========================");
Constructor[] constructors = c1.getConstructors();//获取public构造方法
Constructor[] constructors2 = c1.getDeclaredConstructors();//获取所有public构造方法
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class,int.class,int.class);//获取指定构造方法
}
}
Field
Method
2.5 动态创建对象执行方法
package com.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//动态创建对象,通过反射
public class Demo08 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class a = Class.forName("com.reflection.User");
//通过newInstance方法创建对象
User o = (User) a.newInstance();//本质是调用类的无参构造器
System.out.println(o);//User{name='null', id=0, age=0}
//通过指定构造器创建对象
Constructor constructor = a.getConstructor(String.class, int.class, int.class);
User zhucheng = (User) constructor.newInstance("zhucheng", 1, 10);
System.out.println(zhucheng);//User{name='zhucheng', id=1, age=10}
//通过反射调用方法
Method setName = a.getMethod("setName", String.class);
setName.invoke(o,"jack");
System.out.println(o);
//通过反射操作属性
User o2 = (User) a.newInstance();
Field name = a.getDeclaredField("name");
name.setAccessible(true);//修改私有属性会报错,需设置成true,关闭程序安全检测
name.set(o2,"haha");
System.out.println(o2);
}
}
反射性能
package com.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/*普通方法耗时:5ms
反射方法耗时:2456ms
反射方法关闭安全检测耗时:1295ms*/
//反射性能问题
public class Demo09 {
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
test01();
test02();
test03();
}
//普通方法调用
public static void test01(){
User user = new User();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
user.getName();
}
long finish = System.currentTimeMillis();
System.out.println("普通方法耗时:"+(finish-start)+"ms");
}
//反射方法调用
public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName",null);
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user);
}
long finish = System.currentTimeMillis();
System.out.println("反射方法耗时:"+(finish-start)+"ms");
}
//普通方法调用
public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
User user = new User();
Class c1 = user.getClass();
Method getName = c1.getDeclaredMethod("getName",null);
getName.setAccessible(true);
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000000; i++) {
getName.invoke(user);
}
long finish = System.currentTimeMillis();
System.out.println("反射方法关闭安全检测耗时:"+(finish-start)+"ms");
}
}
2.6 获取泛型信息
2.7 获取注解信息
package com.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class Demo10 {
public static void main(String[] args) throws NoSuchFieldException {
Class<students> s = students.class;
//通过反射获得注解
Annotation[] annotations = s.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation); //@com.reflection.TableStudents(value=db_students)
}
//获取注解值
TableStudents annotation = s.getAnnotation(TableStudents.class);
String value = annotation.value();
System.out.println(value); //db_students
//获取属性上的注解
Field name = s.getDeclaredField("name");
FieldStudents annotation1 = name.getAnnotation(FieldStudents.class);
System.out.println(annotation1.columnName());//db_name
System.out.println(annotation1.length());//3
System.out.println(annotation1.type());//varchar
}
}
@TableStudents("db_students")
class students{
@FieldStudents(columnName = "db_id",type = "int",length = 10)
private int id;
@FieldStudents(columnName = "db_age",type = "int",length = 10)
private int age;
@FieldStudents(columnName = "db_name",type = "varchar",length = 3)
private String name;
public students() {
}
public students(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 "students{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
//类名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableStudents{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldStudents{
String columnName();
String type();
int length();
}
2.8 文件路径(补充)
获取文件绝对路径