注解与反射
注解与反射
注解
什么是注解
- Annotation是JDK5.0开始引入的新技术
- Annotation可以被其它程序读取,通过反射可以读取注解的信息
内置注解
- @Override:重写方法
- @Deprecated:建议不使用改方法
- @SuppressWarnings("all"):抑制警告
package com.edgar.annotation;
import java.util.ArrayList;
@SuppressWarnings("all")//抑制警告
public class Test01 extends Object{
@Override//重写方法
public String toString() {
return super.toString();
}
@Deprecated//建议不使用改方法
public static void test(){
System.out.println("Deprecated");
}
public static void main(String[] args) {
test();
}
}
元注解
什么是元注解?
元注解是对注解的注解
四大元注解
- @Target:表示我们的注解可以用在那个地方
- @Retention:表示我们的注解在什么时候还有效
- @Documented:表示是否将我们的注解生成在JavaDoc中
- @Inherited:表示子类可以继承父类的注解
package com.edgar.annotation;
import java.lang.annotation.*;
@MyAnnotation
public class Test02 {
public void test() {
}
}
//元注解:对注解的注解(Target、Retention、Documented、Inherited)
//定义一个注解
//Target 表示我们的注解可以用在那个地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention 表示我们的注解在什么时候还有效
//runtime>class>source
@Retention(RetentionPolicy.RUNTIME)
//Documented 表示是否将我们的注解生成在JAVADoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation {
}
反射
什么是反射
Reflection是java语言被称作动态语言的关键。
-
通过反射获取类的Class对象
-
一个类在内存中只有一个Class对象
-
一个类被加载后,类的整个结构都会被封装到Class对象
Class类的创建方式
package com.edgar.reflection;
//测试Class类的创建方式有哪些
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException {
Student student = new Student();
//方式一:通过对象获得
Class c1 = student.getClass();
System.out.println(c1.hashCode());
//方式二:通过forName获得
Class c2 = Class.forName("com.edgar.reflection.Student");
System.out.println(c2.hashCode());
//方式三:通过类名.class获得
Class c3 = Student.class;
System.out.println(c3.hashCode());
//方式四:基本内置类型的包装类都有一个TYPE属性
Class c4 = Integer.TYPE;
System.out.println(c4);
//获得父类类对象
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person {
String name;
public Person(String name) {
this.name = name;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person {
}
所有类型的Class
package com.edgar.reflection;
import java.lang.annotation.ElementType;
//所有类型的Class
public class Test03 {
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[12];
System.out.println(a.getClass().hashCode());
System.out.println(b.getClass().hashCode());
}
}
java类什么时候加载
1.实例化对象时,就像spring管理的bean一样,在tomcat启动时就实例化了bean,那么这个对象bean的类就加载了
2.通过类名调用静态变量的时候(类名.class除外)
类加载内存分析
-
加载:将class文件加载到内存中,生成代表这个类的java.lang.Class对象
-
链接:
- 验证:确保加载的类信息符合JVM规范
- 准备:为类变量(static)分配内存空间,并设置初始值为默认值(0,0.0,null等)
- 解析:虚拟机常量池内的常量名替换为引用地址
-
初始化:执行类构造器的
()方法。类构造器的 ()方法是在编译阶段自动收集所有类变量、静态代码块合并后的方法。合并的顺序为自上而下。 如果初始化一个类时,发现父类没有初始化,会先初始化父类。
类加载器
package com.edgar.reflection;
//类加载器
public class Test06 {
public static void main(String[] args) throws ClassNotFoundException {
//获取系统类的加载器-->应用程序加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
//获取系统类加载器的父类加载器-->扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
//获取扩展类加载器的父类加载器-->根加载器
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
//获取当前类是哪个加载器加载的
ClassLoader c1 = Class.forName("com.edgar.reflection.Test06").getClassLoader();
System.out.println(c1);
//测试JDK内置的类是谁加载的
ClassLoader c2 = Class.forName("java.lang.Object").getClassLoader();
System.out.println(c2);
//如何获取系统类加载器可以加载的路径
String property = System.getProperty("java.class.path");
System.out.println(property);
//双亲委派机制:创建对象后先向上找包,找不到再用自己的
//自己定义的java.lang.String,包名+类名都一样,通过双亲委派机制,会使用rt包下的java.lang.String
/*
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\charsets.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\deploy.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\access-bridge-64.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\cldrdata.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\dnsns.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\jaccess.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\jfxrt.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\localedata.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\nashorn.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\sunec.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\sunjce_provider.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\sunmscapi.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\sunpkcs11.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\ext\zipfs.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\javaws.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\jce.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\jfr.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\jfxswt.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\jsse.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\management-agent.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\plugin.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\resources.jar;
C:\Users\86152\Documents\javaTools\jdk\jdk1.8.0_281\jre\lib\rt.jar;
E:\ideaProject\注解与反射\out\production\注解与反射;
C:\Users\86152\Documents\javaTools\IntelliJ IDEA 2020.3.3\lib\idea_rt.jar
*/
}
}
类的运行时结构--通过反射如何获取类的属性、方法、构造器
package com.edgar.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//获得类的运行时结构
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.edgar.reflection.User");
//获得类的名字
System.out.println(c1.getName());//获得包名+类名
System.out.println(c1.getSimpleName());//获得类名
//获得类的属性
System.out.println("========================");
Field[] fields = c1.getFields();//只能找到public属性
for (Field field : fields) {
System.out.println(field);
}
fields = c1.getDeclaredFields();//找到全部的属性
for (Field field : fields) {
System.out.println(field);
}
//获得指定属性
Field field = c1.getDeclaredField("name");
System.out.println(field);
//获得类的方法
System.out.println("========================");
Method[] methods = c1.getMethods();//获得本类和父类的所有public方法
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);
//获得构造器
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);
}
}
动态的创建对象--通过反射如何创建对象
package com.edgar.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//动态的创建对象
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
//获得Class对象
Class c1 = Class.forName("com.edgar.reflection.User");
//构造一个对象
//User user = (User) c1.newInstance();//本质是调用了类的无参构造器
//System.out.println(user);
//通过构造器创建对象
//Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
//User user2 = (User) constructor.newInstance("Edgar", 1, 18);
//System.out.println(user2);
//通过反射调用方法
User user3 = (User) c1.newInstance();
Method setName = c1.getDeclaredMethod("setName", String.class);
//invoke 激活的意思
//(对象,"方法的值")
setName.invoke(user3,"Edgar");
System.out.println(user3.getName());
//通过反射操作属性
System.out.println("====================");
User user4 = (User) c1.newInstance();
Field name = c1.getDeclaredField("name");
//不能直接操作私有属性,我们需要关闭程序的安全检测,属性或方法的setAccessible(true)
name.setAccessible(true);
name.set(user4,"Edgar");
System.out.println(user4.getName());
}
}
分析性能问题
new实例最高效、反射方式调用,关闭程序检测次之,反射方式调用,不关闭程序检测最慢
package com.edgar.reflection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//分析性能问题
public class Test09 {
//普通方式调用
public static void test01(){
User user = new User();
long startTime = System.currentTimeMillis();
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 ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class c1 = Class.forName("com.edgar.reflection.User");
User user = (User) c1.newInstance();
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 ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class c1 = Class.forName("com.edgar.reflection.User");
User user = (User) c1.newInstance();
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 ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
test01();
test02();
test03();
}
}
控制台结果:
普通方式执行10亿次:2ms
反射方式执行10亿次:2305ms
关闭程序检测执行10亿次:1282ms
如何自定义一个注解并通过反射去操作注解
package com.edgar.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
//练习反射操作注解
public class Test11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.edgar.reflection.Student2");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解的value值
TableEdgar tableEdgar = (TableEdgar)c1.getAnnotation(TableEdgar.class);
String value = tableEdgar.value();
System.out.println(value);
//获得类指定的注解
Field name = c1.getDeclaredField("name");
FieldEdgar fieldEdgar = (FieldEdgar)name.getAnnotation(FieldEdgar.class);
System.out.println(fieldEdgar.columnName());
System.out.println(fieldEdgar.type());
System.out.println(fieldEdgar.length());
}
}
@TableEdgar("db_Student")
class Student2{
@FieldEdgar(columnName = "db_id",type = "int",length = 10)
private int id;
@FieldEdgar(columnName = "db_age",type = "int",length = 10)
private int age;
@FieldEdgar(columnName = "db_name",type = "varchar",length = 3)
private String name;
public int getId() {
return id;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public Student2() {
}
public Student2(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}
//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableEdgar{
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldEdgar{
String columnName();
String type();
int length();
}