注解和反射
文章目录
注解
什么是注解
内置注解
package com.lwx.annotation;
import java.util.ArrayList;
import java.util.List;
/**
* @program: 注解和反射
* @description: 内置注解
* 什么是注解
* @author: codelwx
* @create: 2021-01-16 14:15
**/
public class Test01 extends Object{
//@Override 重写的注释
@Override
public String toString() {
return super.toString();
}
@Deprecated
public static void test(){
System.out.println("Deprecated");
}
//@SuppressWarnings 镇压注解,镇压警告
@SuppressWarnings("all")
public void test02(){
List<String> list = new ArrayList<String>();
}
public static void main(String[] args) {
test();
}
}
元注解
package com.lwx.annotation;
import java.lang.annotation.*;
/**
* @program: 注解和反射
* @description: 创建一个元注解
* @author: codelwx
* @create: 2021-01-16 14:49
**/
public class Test02 {
@MyAnnotation
public void test(){}
}
//定义注解
//Target 决定注解使用的地方 ElementType为enum枚举类型:TYPE FIELD METHOD..
@Target(value = ElementType.METHOD)
//Retention 注解生效的范围 RUNTIME运行时>CLASS 编译后 >SOURCE 源码
@Retention(value = RetentionPolicy.RUNTIME)
//Documented表示是否将注解生成再JAVAdoc中
@Documented
//Inherited子类继承父类的注解
@Inherited
@interface MyAnnotation {
}
自定义注解
package com.lwx.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @program: 注解和反射
* @description: 自定义注解
* @author: codelwx
* @create: 2021-01-16 15:03
**/
public class Test03 {
//注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
@MyAnnotation01(name = "刘闻旭")
public void test01(){}
@MyAnnotation02("旭霸霸")
public void test02(){}
}
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation01{
//注解参数的格式:参数类型+参数名()
String name() default "";
int age() default 21;
int id() default -1;//如果默认值为-1,表示不存在。类试indexof()
String[] school() default {"宁波财经学院","数字技术与工程学院"};
}
@Target(value=ElementType.METHOD)
@Retention(value=RetentionPolicy.RUNTIME)
@interface MyAnnotation02{
String value();//只有一个成员参数用value
}
反射
静态 动态语言
反射机制研究及应用
反射的优缺点
反射相关API
package com.lwx.reflection;
/**
* @program: 注解和反射
* @description: 初步了解反射
* @author: codelwx
* @create: 2021-01-17 12:43
**/
public class Test01 {
public static void main(String[] args) throws ClassNotFoundException {
Class c1 = Class.forName("com.lwx.reflection.Test01");
Class c2 = Class.forName("com.lwx.reflection.Test01");
Class c3 = Class.forName("com.lwx.reflection.Test01");
System.out.println(c1);
//一个类的内存中只有一个Class对象
//一个类加载后,类的整个结构都会被封装在class对象中
System.out.println(c1.hashCode());
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
}
}
//创建实体类 pojo entity
class User {
private String userName;
private String password;
private int id;
public int wid;
public User(String userName, String password, int id) {
this.userName = userName;
this.password = password;
this.id = id;
}
public User(){}
private void Test(){}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public int getId() {
return id;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", password='" + password + '\'' +
", id=" + id +
'}';
}
}
Class类
Class类常用方法
获得Class类的实例
package com.lwx.reflection;
/**
* @program: 注解和反射
* @description: class常用方法
* @author: codelwx
* @create: 2021-01-17 12:58
**/
public class Test02 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();//向上转型
System.out.println(person.getName());
//获取class实例
//通过类名.class获得
Class<Student> c1 = Student.class;
System.out.println(c1);
//通过实例对象获得
Class c2 = person.getClass();
System.out.println(c2);
//通过forName(路径)获得
Class c3 = Class.forName("com.lwx.reflection.Teacher");//抛出异常
System.out.println(c3);
//内置类型的包装类都有一个Type属性
Class<Integer> c4 = Integer.TYPE;
System.out.println(c4);
//获得父类类型
Class c5 = c1.getSuperclass();
System.out.println(c5);
}
}
class Person{
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
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{
public Student(){
this.setName("学生");
}
}
class Teacher extends Person{
public Teacher(){
this.setName("老师");
}
}
运行结果:
学生
class com.lwx.reflection.Student
class com.lwx.reflection.Student
class com.lwx.reflection.Teacher
int
class com.lwx.reflection.Person
package com.lwx.reflection;
import java.lang.annotation.ElementType;
/**
* @program: 注解和反射
* @description: 那些类型有class对象
* @author: codelwx
* @create: 2021-01-17 14:11
**/
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[100];
System.out.println(a.hashCode());
System.out.println(b.hashCode());
}
}
运行结果:
interface java.lang.Override
class java.lang.annotation.ElementType
class java.lang.Integer
void
class java.lang.Class
356573597
1735600054
Java内存分析
类的加载过程
类加载器
package com.lwx.reflection;
/**
* @program: 注解和反射
* @description: 类加载顺序
* @author: codelwx
* @create: 2021-01-17 14:34
**/
public class Test04 {
public static void main(String[] args) {
A a = new A();
System.out.println(A.m);
/**
* 1.加载到内存,会创建一个class对象
* 2.链接,结束后m=0
* 3.初始化(合并赋值语句和静态代码)
* <clinit>(){
* int m = 300;
* int m = 100;
* }
* m=100;
*
* </>
* */
}
}
class A{
static {
System.out.println("A类的静态代码块启动");
int m = 300;
}
static int m = 100;
public A() {
System.out.println("A类的无参构造方法启动");
}
}
运行结果:
A类的静态代码块启动
A类的无参构造方法启动
100
package com.lwx.reflection;
/**
* @program: 注解和反射
* @description: 分析类初始化
* @author: codelwx
* @create: 2021-01-17 14:49
**/
public class Test05 {
static {
System.out.println("Main方法加载");
}
public static void main(String[] args) throws ClassNotFoundException {
//主动引用
//new一个对象
//Son son = new Son();
//反射
//Class.forName("com.lwx.reflection.Son");
//不产生类的引用的方法
//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;
}
运行结果:
Main方法加载
1
类加载器的作用
package com.lwx.reflection;
import sun.management.resources.agent;
import sun.tools.jar.resources.jar;
/**
* @program: 注解和反射
* @description: 类加载器
* @author: codelwx
* @create: 2021-01-17 15:33
**/
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 classLoader = Class.forName("com.lwx.reflection.Test06").getClassLoader();
System.out.println(classLoader);
//测试jdk内置类加载器
ClassLoader classLoader1 = Class.forName("java.lang.Object").getClassLoader();
System.out.println(classLoader1);
//如何获得系统类加载器可以加载的路径
System.out.println(System.getProperty("java.class.path"));
/**双亲委派机制:多重检测,保证安全性。检测是否命名重复
双亲委派机制,的确是防止同名包、类与 jdk 中的相冲突,实际上加载类的时候,先通知 appLoader,看 appLoader 是否已经
缓存,没有的话,appLoader 又委派给他的父类加载器(extLoader)询问,看他是不是能已经缓存加载,没有的话,extLoader
又委派他的父类加载器(bootstrapLoader)询问,BootstrapLoader看是不是自己已缓存或者能加载的,有就加载,没有再返回
extLoader,extLoader 能加载就加载,不能的话再返回给 appLoader 加载,再返回的路中,谁能加载,加载的同时也加缓存
当某个类加载器需要加载某个.class文件时,它首先把这个任务委托给他的上级类加载器,递归这个操作,如果上级的类加载器没有加载,自己才会去加载这个类。
* D:\jdk\jdk1.8.0_162\jre\lib\charsets.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\deploy.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\access-bridge-64.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\cldrdata.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\dnsns.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\jaccess.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\jfxrt.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\localedata.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\nashorn.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\sunec.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\sunjce_provider.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\sunmscapi.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\sunpkcs11.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\ext\zipfs.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\javaws.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\jce.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\jfr.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\jfxswt.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\jsse.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\management-agent.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\plugin.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\resources.jar;
* D:\jdk\jdk1.8.0_162\jre\lib\rt.jar;
* D:\idea_work\JavaBase\注解和反射\out\production\注解和反射;
* E:\idea\IntelliJ IDEA 2018.1.4\lib\idea_rt.jar
* */
}
}
运行结果:
sun.misc.Launcher$AppClassLoader@18b4aac2
sun.misc.Launcher$ExtClassLoader@1540e19d
null
sun.misc.Launcher$AppClassLoader@18b4aac2
null
D:\jdk\jdk1.8.0_162\jre\lib\charsets.jar;D:\jdk\jdk1.8.0_162\jre\lib\deploy.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\access-bridge-64.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\cldrdata.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\dnsns.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\jaccess.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\jfxrt.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\localedata.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\nashorn.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\sunec.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\sunjce_provider.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\sunmscapi.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\sunpkcs11.jar;D:\jdk\jdk1.8.0_162\jre\lib\ext\zipfs.jar;D:\jdk\jdk1.8.0_162\jre\lib\javaws.jar;D:\jdk\jdk1.8.0_162\jre\lib\jce.jar;D:\jdk\jdk1.8.0_162\jre\lib\jfr.jar;D:\jdk\jdk1.8.0_162\jre\lib\jfxswt.jar;D:\jdk\jdk1.8.0_162\jre\lib\jsse.jar;D:\jdk\jdk1.8.0_162\jre\lib\management-agent.jar;D:\jdk\jdk1.8.0_162\jre\lib\plugin.jar;D:\jdk\jdk1.8.0_162\jre\lib\resources.jar;D:\jdk\jdk1.8.0_162\jre\lib\rt.jar;D:\idea_work\JavaBase\注解和反射\out\production\注解和反射;E:\idea\IntelliJ IDEA 2018.1.4\lib\idea_rt.jar
小结
Class对象用途
package com.lwx.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @program: 注解和反射
* @description: 获取类运行时结构
* @author: codelwx
* @create: 2021-01-17 19:05
**/
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
//通过反射获取User对象
Class c1 = Class.forName("com.lwx.reflection.User");
//获取类的名字
System.out.println(c1.getName());//获取包名+类名
System.out.println(c1.getSimpleName());//获取类名
//获取类的属性
Field[] fields = c1.getFields();//只能找到public属性(包括父类)
for (Field field : fields) {
System.out.println("正常:" + field);
}
fields = c1.getDeclaredFields();//本类全部属性
for (Field field : fields) {
System.out.println("getFields:" + 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 getUserName = c1.getMethod("setUserName", String.class);
Method getId = c1.getMethod("setId", int.class);
System.out.println(getUserName);
System.out.println(getId);
//获得指定的构造器
Constructor[] constructors = c1.getConstructors();//只能找到public属性(包括父类)
for (Constructor constructor : constructors) {
System.out.println("正常:" + constructor);
}
constructors = c1.getDeclaredConstructors();//本类全部属性
for (Constructor constructor : constructors) {
System.out.println("getDeclaredConstructors:" + constructor);
}
//获得指定的构造方法
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, String.class, int.class);
System.out.println("getDeclaredConstructor:" + declaredConstructor);
}
}
运行结果:
public void com.lwx.reflection.User.setUserName(java.lang.String)
public void com.lwx.reflection.User.setId(int)
正常:public com.lwx.reflection.User(java.lang.String,java.lang.String,int)
正常:public com.lwx.reflection.User()
getDeclaredConstructors:public com.lwx.reflection.User(java.lang.String,java.lang.String,int)
getDeclaredConstructors:public com.lwx.reflection.User()
getDeclaredConstructor:public com.lwx.reflection.User(java.lang.String,java.lang.String,int)
调用指定的方法
package com.lwx.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @program: 注解和反射
* @description: 动态创建对象和执行方法
* @author: codelwx
* @create: 2021-01-17 19:56
**/
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
Class c1 = Class.forName("com.lwx.reflection.User");
//构造对象
//User user = (User) c1.newInstance();
//System.out.println(user);
//通过构造器创建对象
//Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, String.class, int.class);
//User user2 = (User) declaredConstructor.newInstance("二哈", "123", 1);
//System.out.println(user);
//通过反射调用普通方法
User user3 = (User) c1.newInstance();
Method setUserName = c1.getDeclaredMethod("setUserName", String.class);
//invoke:激活
//(对象,"方法的值")
setUserName.invoke(user3,"二哈");
System.out.println(user3.getUserName());//二哈
//通过反射操作属性
User user4 = (User) c1.newInstance();
Field userName = c1.getDeclaredField("userName");
//启用和禁用安全检测开关
userName.setAccessible(true);//不能直接操作私有属性,我们需要关闭程序的安全检测,属性或方法setAccessible(true)
//(对象,"方法的值")
userName.set(user4,"二哈00");
System.out.println(user4.getUserName());
}
}
运行结果:
二哈
二哈00
反射操作泛型
package com.lwx.reflection;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
/**
* @program: 注解和反射
* @description: 获取泛型信息
* @author: codelwx
* @create: 2021-01-17 20:51
**/
public class Test10 {
public void myTest01(Map<String, User> map, List<User> list) {
System.out.println("myTest01");
}
public Map<String, User> myTest02() {
System.out.println("myTest02");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method myTest01 = Test10.class.getDeclaredMethod("myTest01", Map.class, List.class);
Type[] genericParameterTypes = myTest01.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 myTest02 = Test10.class.getDeclaredMethod("myTest02", null);
Type genericParameterTypes1 = myTest02.getGenericReturnType();
if (genericParameterTypes1 instanceof ParameterizedType) {
Type[] actualTypeArguments = ((ParameterizedType) genericParameterTypes1).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
}
}
运行结果:
java.util.Map<java.lang.String, com.lwx.reflection.User>
class java.lang.String
class com.lwx.reflection.User
java.util.List<com.lwx.reflection.User>
class com.lwx.reflection.User
class java.lang.String
class com.lwx.reflection.User
反射操作注解
- getAnnotations
- getAnnotation
package com.lwx.reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
/**
* @program: 注解和反射
* @description: 反射操作注解
* @author: codelwx
* @create: 2021-01-18 13:09
**/
public class Test11 {
//通过反射获取注解
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.lwx.reflection.Student01");
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获取注解的value值
MyAnnotation myAnnotation = (MyAnnotation) c1.getAnnotation(MyAnnotation.class);
String value = myAnnotation.value();
System.out.println(value);
//获得类指定的注解
Field name = c1.getDeclaredField("name");
MyField annotation = name.getAnnotation(MyField.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
//创建注解(类型注解)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String value();
}
//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface MyField {
String columnName();
String type();
int length();
}
@MyAnnotation("db_student")
class Student01 {
@MyField(columnName = "db_id", type = "int", length = 10)
private int id;
@MyField(columnName = "db_age", type = "int", length = 10)
private int age;
@MyField(columnName = "db_name", type = "String", length = 20)
private String name;
public Student01() {
}
public Student01(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 "student{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
运行结果:
@com.lwx.reflection.MyAnnotation(value=db_student)
db_student
db_name
String
20