1、注解入门
1.1、什么是注解
第一个注解代码:
//什么是注解
public class Test01 extends Object {
//@Override 重写的注解
@Override
public String toString() {
return super.toString();
}
}
1.2、内置注解
1.3、元注解
代码解释:
//测试元注解
public class Test02 {
}
//定义一个注解
//Target 表示我们的注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})
//Retention 表示我们的注解在什么地方还有效
//runtime > class > sources
@Retention(value = RetentionPolicy.RUNTIME)
//Documented 表示是否将我们的注解生产在JAVAdoc中
@Documented
//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}
1.4、自定义注解
代码实现:
//自定义注解
public class Test03 {
//注解可以显示赋值,如果没有赋值,我们就必须给注解赋值
@MyAnnotation2(age = 18,name = "吴寅亮")
public void test(){}
@MyAnnotation3("吴寅亮")
public void test2(){}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
//注解的参数:参数类型+参数名();
String name() default "";
int age();
int id() default -1;//如果默认值为-1,代表不存在。
String[] schools() default {"银月授面","安徽大学"};
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
String value();
}
二、反射机制
2.1、静态 VS 动态语言
2.2、Java Reflection
2.3、Java反射机制及应用
2.4、Java反射优点和缺点
2.5、反射相关的主要API
反射的一个小例子:
package com.kuang.demo.demo01;
//什么叫反射
public class Test001 {
public static void main(String[] args) throws ClassNotFoundException {
//通过反射获取类的class对象
Class c1 = Class.forName("com.kuang.demo.demo01.User");
System.out.println(c1);
//一个类在内存中只有一个class对象
//一个类被加载后,类的整个结构都会被封装在Class对象中
Class c2 = Class.forName("com.kuang.demo.demo01.User");
Class c3 = Class.forName("com.kuang.demo.demo01.User");
Class c4 = Class.forName("com.kuang.demo.demo01.User");
System.out.println(c2.hashCode());
System.out.println(c3.hashCode());
System.out.println(c4.hashCode());
}
}
//实体类:pojo entity
class User{
private String name;
private int id;
protected 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.6、Class类
2.7、Class类常用的方法
2.8、获取Class类的实例
几种获得方式的代码实现:
package com.kuang.demo.demo01;
//测试Class类的创建方式有哪些
public class Test002 {
public static void main(String[] args) throws ClassNotFoundException {
Person person = new Student();
System.out.println("这个人是:" + person.name);
//方式一:通过对象获得
Class c1 = person.getClass();
System.out.println(c1.hashCode());
//方式二:forname获得
Class c2 = Class.forName("com.kuang.demo.demo01.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{
public String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
class Student extends Person{
public Student(){
this.name = "学生";
}
}
class Teacher extends Person{
public Teacher(){
this.name = "老师";
}
}
运行结果:
2.9、哪些类型可以有Class对象?
代码实现:
package com.kuang.demo.demo01;
import java.lang.annotation.ElementType;
//所有类型的Class
public class Test003 {
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.10、Java内存分析
2.11、了解类的加载过程
2.12、类的加载与ClassLoader的理解
例子说明:
package com.kuang.demo.demo01;
public class Test004 {
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类静态代码块初始化");
* m = 300;
* m=100;
* }
*
* m = 100
* */
}
}
class A{
static {
System.out.println("A类静态代码块初始化");
m = 300;
}
/*m=300
* m=100
* */
static int m = 100;
public A(){
System.out.println("A类的无参构造初始化");
}
}
运行结果:
对运行结果中的过程进行绘图分析:
2.13、什么时候会发生类初始化?
代码例子:
package com.kuang.demo.demo01;
//测试类什么时候会初始化
public class Test005 {
static {
System.out.println("Main类被加载");
}
public static void main(String[] args) throws ClassNotFoundException {
//1.主动引用
//Son son = new Son();
//反射也会产生主动引用
Class.forName("com.kuang.demo.demo01.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;
}
2.14、类加载器的作用
代码实现:
package com.kuang.demo.demo01;
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException {
//获取系统类的加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
//获取系统类加载器的父类加载器--》扩展类加载器
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
//获取扩展类加载器的父类加载器-->根加载器(C/C++)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
//测试当前类是哪个加载器加载的
ClassLoader classLoader = Class.forName("com.kuang.demo.demo01.Test07").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:\Program Files\Java\jdk1.8.0_171\jre\lib\charsets.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\deploy.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\access-bridge-64.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\cldrdata.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\dnsns.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jaccess.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\jfxrt.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\localedata.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\nashorn.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunec.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunjce_provider.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunmscapi.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\sunpkcs11.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\ext\zipfs.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\javaws.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\jce.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfr.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\jfxswt.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\jsse.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\management-agent.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\plugin.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\resources.jar;
C:\Program Files\Java\jdk1.8.0_171\jre\lib\rt.jar;G:\项目练习\untitled1\out\production\untitled1;
G:\项目练习\untitled1\src\com\lib\commons-io-2.6.jar;F:\IDEAtools\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar
* */
}
}
运行结果:
2.15、获取运行时类的完整结构
代码例子:
package com.kuang.demo.demo01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//获得类的信息
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.kuang.demo.demo01.User");
//获得类的名字
System.out.println(c1.getName()); //获得包名 + 类名
System.out.println(c1.getSimpleName()); // 获得类名
//获得类的属性
System.out.println("===========================");
Field[] fields = c1.getFields(); //只能找到public属性
fields = c1.getDeclaredFields(); //找到全部的属性
for(Field field:fields){
System.out.println(field);
}
//获得指定属性的值
Field name = c1.getDeclaredField("name");
System.out.println(name);
//获得类的方法
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);
}
}
运行结果图:
2.16、小结
2.17、有了Class对象,能做什么?
调用指定方法:
setAssessicble:
代码实现:
package com.kuang.demo.demo01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//动态的创建对象,通过反射
public class Test09 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
//获得Class对象
Class c1 = Class.forName("com.kuang.demo.demo01.User");
// //构造一个对象
// User user = (User)c1.newxInstance(); //本质是调用了类的无参构造器
// System.out.println(user);
//通过构造器创建对象
Constructor Constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
User user2 =(User) Constructor.newInstance("吴寅亮", 001, 18);
System.out.println(user2);
//通过反射调用普通方法
User user3 = (User)c1.newInstance();
//通过反射获取一个方法
Method setName = c1.getDeclaredMethod("setName", String.class);
//invoke:激活的意思
//(对象,"方法的值"
setName.invoke(user3,"小吴");
System.out.println(user3.getName());
//通过反射操作属性
System.out.println("888888888888888888888888888888");
User user4 = (User)c1.newInstance();
Field name = c1.getDeclaredField("name");
name.setAccessible(true);
name.set(user4,"小吴2");
System.out.println(user4.getName());
}
}
运行结果:
2.18、性能比较
普通方法调用,反射方法调用和反射方法调用后的检测关闭三种方式的性能比较:
package com.kuang.demo.demo01;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
//分析性能问题
public class Test10 {
//普通方式调用
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 InvocationTargetException, IllegalAccessException, NoSuchMethodException {
User user = new User();
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 InvocationTargetException, IllegalAccessException, NoSuchMethodException {
User user = new User();
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 IllegalAccessException, NoSuchMethodException, InvocationTargetException {
test01();
test02();
test03();
}
}
运行结果图:
2.19、反射操作泛型
反射操作泛型代码:
package com.kuang.demo.demo01;
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 Test12 {
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 = Test12.class.getMethod("test01", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("#" + genericParameterTypes);
if(genericParameterTypes instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArguments);
}
}
}
method = Test12.class.getMethod("test02",null);
Type genericReturnType = method.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArguments);
}
}
}
}
运行结果:
2.20、反射操作注解
练习------ORM
代码实现:
package com.kuang.demo.demo01;
import java.lang.annotation.*;
import java.lang.reflect.Field;
//练习反射操作注解
public class Test13 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class c1 = Class.forName("com.kuang.demo.demo01.Student2");
//通过反射获得注解
Annotation[] annotations = c1.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotations);
}
//获得注解的value的值
Tablekuang tablekuang = (Tablekuang) c1.getAnnotation(Tablekuang.class);
String value = tablekuang.value();
System.out.println(value);
//获得类指定的注解
Field f = c1.getDeclaredField("name");
Filedkuang annotation = f.getAnnotation(Filedkuang.class);
System.out.println(annotation.columnName());
System.out.println(annotation.type());
System.out.println(annotation.length());
}
}
@Tablekuang("db_student")
class Student2{
@Filedkuang(columnName = "db_id",type = "int",length = 10)
private int id;
@Filedkuang(columnName = "db_age",type = "int",length = 10)
private int age;
@Filedkuang(columnName = "db_name",type = "varchar",length = 3)
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 Tablekuang{
String value();
}
//属性的注解
@interface Filedkuang{
String columnName();
String type();
int length();
}
运行结果: