1、昨日复习

  1. 一个IP对应着哪个类的一个对象?InetAddress
    实例化这个类的两种方式是?
    InetAddress.getByName(String host);
    InetAddress.getLocalHost();//获取本地ip
    两个常用的方法是?
    getHostName();
    getHostAddress();
    2. 传输层的TCP协议和UDP协议的主要区别是?
    TCP:可靠的数据传输(三次握手);进行大数据量的传输;效率低

UDP:不可靠;以数据报形式发送,数据报限定为64k;效率高

  1. 什么是URL,你能写一个URL吗?
    URL:统一资源定位符
    URL url = new
    URL(“http://192.168.14.100:8080/examples/hello.txt?username=Tom”);
    4. 谈谈你对对象序列化机制的理解
    序列化过程:
    反序列化过程:
    5. 对象要想实现序列化,需要满足哪几个条件
    1. 实现接口:Serializable 标识接口
    2. 对象所在的类提供常量:序列版本号
    3. 要求对象的属性也必须是可序列化的。(基本数据类型、String:本身就已经是可序列化的。)

    2、反射机制概述

    Reflection(反射)是被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。
    加载完类之后,在堆内存的方法区中就产生了一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看
    到类的结构,所以,我们形象的称之为:反射
    QQ截图20220127155203.png
    QQ截图20220127155309.png
    Java反射机制提供的功能
    在运行时判断任意一个对象所属的类
    在运行时构造任意一个类的对象
    在运行时判断任意一个类所具有的成员变量和方法
    在运行时获取泛型信息
    在运行时调用任意一个对象的成员变量和方法
    在运行时处理注解
    生成动态代理

    3、理解Class类并获取Class的实例

    ```java package com.atguigu.java1;

public class Person { private String name; public int age;

  1. public Person() {
  2. System.out.println("我是空参构造器");
  3. }
  4. public Person(String name, int age) {
  5. this.name = name;
  6. this.age = age;
  7. }
  8. private Person(String name) {
  9. this.name = name;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public int getAge() {
  18. return age;
  19. }
  20. public void setAge(int age) {
  21. this.age = age;
  22. }
  23. @Override
  24. public String toString() {
  25. return "Person{" +
  26. "name='" + name + '\'' +
  27. ", age=" + age +
  28. '}';
  29. }
  30. public void show(){
  31. System.out.println("你好,我是一个人");
  32. }
  33. private String showNation(String nation){
  34. System.out.println("我的国籍是:"+nation);
  35. return nation;
  36. }

}

  1. ```java
  2. package com.atguigu.java1;
  3. import org.junit.Test;
  4. import java.lang.annotation.ElementType;
  5. import java.lang.reflect.Constructor;
  6. import java.lang.reflect.Field;
  7. import java.lang.reflect.InvocationTargetException;
  8. import java.lang.reflect.Method;
  9. public class ReflectionTest {
  10. //反射之前,对于Person类的操作
  11. @Test
  12. public void test1() {
  13. //1、创建Person类的对象
  14. Person p1 = new Person("Tom", 12);
  15. //2、通过对象,调用其内部的属性、方法
  16. p1.age = 10;
  17. System.out.println(p1.toString());
  18. p1.show();
  19. //在Person类外部,不可以通过Person类的对象调用其内部私有结构
  20. //比如:name、showNation以及私有的构造器
  21. }
  22. //反射之后,对于Person类的操作
  23. @Test
  24. public void test2() throws Exception {
  25. Class clazz = Person.class;
  26. //1、通过反射创建Person类的对象
  27. Constructor cons = clazz.getConstructor(String.class, int.class);
  28. Object obj = cons.newInstance("Tom", 12);
  29. Person p = (Person) obj;
  30. System.out.println(p.toString());
  31. //2、通过反射,调用对象指定的属性、方法
  32. //调属性
  33. Field age = clazz.getDeclaredField("age");
  34. age.set(p, 10);
  35. System.out.println(p.toString());
  36. //调方法
  37. Method show = clazz.getDeclaredMethod("show");
  38. show.invoke(p);
  39. //通过反射,可以调用Person类的私有结构。比如:私有的构造器、方法、属性
  40. //调用私有的构造器
  41. Constructor cons1 = clazz.getDeclaredConstructor(String.class);
  42. cons1.setAccessible(true);
  43. Person p1 = (Person) cons1.newInstance("Jerry");
  44. System.out.println(p1);
  45. //调用私有的属性
  46. Field name = clazz.getDeclaredField("name");
  47. name.setAccessible(true);
  48. name.set(p1,"HanMeimei");
  49. System.out.println(p1);
  50. //调用私有的方法
  51. Method showNation = clazz.getDeclaredMethod("showNation", String.class);
  52. showNation.setAccessible(true);
  53. String nation = (String) showNation.invoke(p1, "中国");//相当于p1.showNation("中国")
  54. System.out.println(nation);
  55. }
  56. //疑问1:通过直接new的方式或反射的方式都可以调用公共的结构,开发中到底用哪个?
  57. //建议:直接new的方式。
  58. //什么时候会使用:反射的方式。反射的特征:动态性
  59. //疑问2:反射机制与面向对象的封装性是不是矛盾的?如何看待两个技术?
  60. //不矛盾。
  61. /*
  62. 关于java.lang.Class类的理解
  63. 1、类的加载过程:
  64. 程序经过javac.exe命令以后,会生成一个或多个字节码文件(.class结尾)。
  65. 接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件
  66. 加载到内存中。此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此
  67. 运行时类,就作为Class的一个实例。
  68. 2、换句话说,Class的实例就对应着一个运行时类。
  69. 3、加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式
  70. 来获取次运行时类。
  71. */
  72. //获取Class类的实例(四种方法)掌握
  73. @Test
  74. public void test3() throws ClassNotFoundException {
  75. //方式一:调用运行时类的属性:.class
  76. Class clazz1 = Person.class;
  77. System.out.println(clazz1);
  78. //方式二:通过运行时类的对象
  79. Person p1 = new Person();
  80. Class clazz2 = p1.getClass();
  81. System.out.println(clazz2);
  82. //方式三:调用Class的静态方法:forName(String classPath)
  83. Class clazz3 = Class.forName("com.atguigu.java1.Person");
  84. System.out.println(clazz3);
  85. System.out.println(clazz1==clazz2);
  86. System.out.println(clazz1==clazz3);
  87. //方式四:使用类的加载器:ClassLoader
  88. ClassLoader classLoader = ReflectionTest.class.getClassLoader();
  89. Class clazz4 = classLoader.loadClass("com.atguigu.java1.Person");
  90. System.out.println(clazz4);
  91. }
  92. //Class实例可以是哪些结构的说明
  93. @Test
  94. public void test4(){
  95. Class c1 = Object.class;
  96. Class c2 = Comparable.class;
  97. Class c3 = String[].class;
  98. Class c4 = int[][].class;
  99. Class c5 = ElementType.class;
  100. Class c6 = Override.class;
  101. Class c7 = int.class;
  102. Class c8 = void.class;
  103. Class c9 = Class.class;
  104. int[] a = new int[10];
  105. int[] b = new int[100];
  106. Class c10 = a.getClass();
  107. Class c11 = b.getClass();
  108. // 只要数组元素类型与维度一样,就是同一个Class
  109. System.out.println(c10 == c11);
  110. }
  111. }

QQ截图20220419203050.png

4、类的加载与ClassLoader的理解

QQ截图20220419203203.png
QQ截图20220419203348.png
QQ截图20220419203545.png

  1. package com.atguigu.java1;
  2. import org.junit.Test;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.util.Properties;
  8. /*
  9. 了解类的加载器
  10. */
  11. public class ClassLoaderTest {
  12. @Test
  13. public void test1(){
  14. //对于自定义类,使用系统加载器进行加载
  15. ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
  16. System.out.println(classLoader);
  17. //调用系统类加载器的getParent():获得扩展类加载器
  18. ClassLoader classLoader1 = classLoader.getParent();
  19. System.out.println(classLoader1);
  20. //调用扩展类加载器的getParent():无法获取引导类加载器
  21. //引导类加载器主要负责加载java的核心类库,无法加载自定义类的
  22. ClassLoader classLoader2 = classLoader1.getParent();
  23. System.out.println(classLoader2);
  24. ClassLoader classLoader3 = String.class.getClassLoader();
  25. System.out.println(classLoader3);
  26. }
  27. /*
  28. Properties:用来读取配置文件。
  29. */
  30. @Test
  31. public void test2() throws IOException {
  32. Properties pros = new Properties();
  33. //此时文件默认在当前module下。
  34. //读取配置文件方式一:
  35. FileInputStream fis = new FileInputStream("jdbc.properties");
  36. pros.load(fis);
  37. //读取配置文件方式二:使用ClassLoader
  38. //配置文件默认识别为当前module的src下
  39. // ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
  40. // InputStream is = classLoader.getResourceAsStream("jdbc1.properties");
  41. // pros.load(is);
  42. String user = pros.getProperty("user");
  43. String password = pros.getProperty("password");
  44. System.out.println("user="+user+",password="+password);
  45. }
  46. }

QQ截图20220419203620.png
QQ截图20220419203643.png

5、创建运行时类的对象

  1. package com.atguigu.java1;
  2. import org.junit.Test;
  3. import java.util.Random;
  4. /*
  5. 通过反射创建对应的运行时类的对象
  6. */
  7. public class NewInstanceTest {
  8. @Test
  9. public void test1() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
  10. ClassLoader classLoader = NewInstanceTest.class.getClassLoader();
  11. Class<Person> clazz = (Class<Person>) classLoader.loadClass("com.atguigu.java1.Person");
  12. /*
  13. newInstance():调用此方法,创建对应的运行时类的对象。内部调用了运行时类的空参构造器
  14. 要想此方法正常的创建运行时类的对象,要求:
  15. 1、运行时类必须提供空参构造器
  16. 2、空参的构造器的访问权限得够。通常,设置为public。
  17. 在javabean中要求提供一个public的空参构造器。原因:
  18. 1、便于通过反射,创建运行时类的对象
  19. 2、便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
  20. */
  21. Person obj = (Person) clazz.newInstance();
  22. System.out.println(obj);
  23. }
  24. //体会反射的动态性
  25. @Test
  26. public void test2() {
  27. for (int i = 0; i < 100; i++) {
  28. int num = new Random().nextInt(3);
  29. String classPath = "";
  30. switch (num) {
  31. case 0:
  32. classPath = "java.util.Date";
  33. break;
  34. case 1:
  35. classPath = "java.lang.Object";
  36. break;
  37. case 2:
  38. classPath = "com.atguigu.java1.Person";
  39. break;
  40. default:
  41. break;
  42. }
  43. try {
  44. Object obj = getInstance(classPath);
  45. System.out.println(obj);
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. }
  49. }
  50. }
  51. /*
  52. 创建一个指定类的对象
  53. classPath:指定类的全类名
  54. */
  55. public Object getInstance(String classPath) throws Exception {
  56. Class clazz = Class.forName(classPath);
  57. return clazz.newInstance();
  58. }
  59. }

6、获取运行时类的完整结构(了解)

  1. package com.atguigu.java3;
  2. import com.atguigu.java2.Person;
  3. import org.junit.Test;
  4. import java.lang.reflect.Field;
  5. import java.lang.reflect.Modifier;
  6. /*
  7. 获取当前运行时类的属性结构
  8. */
  9. public class FileTest {
  10. @Test
  11. public void test1(){
  12. Class<Person> clazz = Person.class;
  13. //获取属性结构
  14. //getFiles():获取当前运行时类及其父类中声明为public访问权限的属性
  15. Field[] fields = clazz.getFields();
  16. for (Field f:fields){
  17. System.out.println(f);
  18. }
  19. System.out.println("************************");
  20. //getDeclaredFields():获取当前运行时类中声明的所有的属性。(不包含父类中声明的属性)
  21. Field[] declaredFields = clazz.getDeclaredFields();
  22. for (Field f:declaredFields){
  23. System.out.println(f);
  24. }
  25. }
  26. //权限修饰符 数据类型 变量名
  27. @Test
  28. public void test2(){
  29. Class<Person> clazz = Person.class;
  30. Field[] declaredFields = clazz.getDeclaredFields();
  31. for (Field f:declaredFields){
  32. //1、权限修饰符
  33. int modifiers = f.getModifiers();
  34. System.out.print(Modifier.toString(modifiers)+"\t");
  35. //2、数据类型
  36. Class<?> type = f.getType();
  37. System.out.print(type.getName()+"\t");
  38. //3、变量名
  39. String fName = f.getName();
  40. System.out.print(fName);
  41. System.out.println();
  42. }
  43. }
  44. }
  1. package com.atguigu.java3;
  2. import com.atguigu.java2.Person;
  3. import org.junit.Test;
  4. import java.lang.annotation.Annotation;
  5. import java.lang.reflect.Method;
  6. import java.lang.reflect.Modifier;
  7. /*
  8. 获取运行时类的方法结构
  9. */
  10. public class MethodTest {
  11. @Test
  12. public void test1() {
  13. Class<Person> clazz = Person.class;
  14. //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
  15. Method[] methods = clazz.getMethods();
  16. for (Method m : methods) {
  17. System.out.println(m);
  18. }
  19. System.out.println("************************************");
  20. //getDeclaredMethods():获取当前运行时类中声明的所有方法。(不包含父类中声明的方法)
  21. Method[] declaredMethods = clazz.getDeclaredMethods();
  22. for (Method m : declaredMethods) {
  23. System.out.println(m);
  24. }
  25. }
  26. /*
  27. 权限修饰符 返回值类型 方法名(参数类型1 形参名1,.....) throws XxxException{}
  28. */
  29. @Test
  30. public void test2() {
  31. Class<Person> clazz = Person.class;
  32. Method[] declaredMethods = clazz.getDeclaredMethods();
  33. for (Method m : declaredMethods) {
  34. //1、获取方法声明的注解
  35. Annotation[] annos = m.getAnnotations();
  36. for (Annotation a : annos) {
  37. System.out.println(a);
  38. }
  39. //2、获取权限修饰符
  40. System.out.print(Modifier.toString(m.getModifiers()) + "\t");
  41. //3、返回值类型
  42. System.out.print(m.getReturnType().getName() + "\t");
  43. //4、方法名
  44. System.out.print(m.getName());
  45. System.out.print("(");
  46. //5、形参列表
  47. Class[] parameterTypes = m.getParameterTypes();
  48. if (!(parameterTypes == null && parameterTypes.length == 0)) {
  49. for (int i=0;i<parameterTypes.length;i++){
  50. if (i==parameterTypes.length-1){
  51. System.out.print(parameterTypes[i].getName()+" args_"+i);
  52. break;
  53. }
  54. System.out.print(parameterTypes[i].getName()+" args_"+i+",");
  55. }
  56. }
  57. System.out.print(")");
  58. //6、抛出的异常
  59. Class[] exceptionTypes = m.getExceptionTypes();
  60. // if (!(exceptionTypes==null&&exceptionTypes.length==0)){
  61. // System.out.print("throws ");
  62. // for (int i = 0; i < exceptionTypes.length; i++) {
  63. // if (i==exceptionTypes.length-1){
  64. // System.out.println(exceptionTypes[i].getName());
  65. // break;
  66. // }
  67. // System.out.println(exceptionTypes[i].getName()+",");
  68. // }
  69. // }
  70. if (exceptionTypes.length>0){
  71. System.out.print("throws ");
  72. for (int i = 0; i < exceptionTypes.length; i++) {
  73. if (i==exceptionTypes.length-1){
  74. System.out.print(exceptionTypes[i].getName());
  75. break;
  76. }
  77. System.out.print(exceptionTypes[i].getName()+",");
  78. }
  79. }
  80. System.out.println();
  81. }
  82. }
  83. }
  1. package com.atguigu.java3;
  2. import com.atguigu.java2.Person;
  3. import org.junit.Test;
  4. import java.lang.annotation.Annotation;
  5. import java.lang.reflect.Constructor;
  6. import java.lang.reflect.ParameterizedType;
  7. import java.lang.reflect.Type;
  8. public class OtherTest {
  9. /*
  10. 获取构造器结构
  11. */
  12. @Test
  13. public void test1() {
  14. Class<Person> clazz = Person.class;
  15. //getConstructors():获取当前运行时类中声明为public的构造器
  16. Constructor[] constructors = clazz.getConstructors();
  17. for (Constructor c : constructors) {
  18. System.out.println(c);
  19. }
  20. System.out.println();
  21. //getDeclaredConstructors():获取当前运行时类中声明的所有构造器。
  22. Constructor<?>[] declaredConstructors = clazz.getDeclaredConstructors();
  23. for (Constructor c : declaredConstructors) {
  24. System.out.println(c);
  25. }
  26. }
  27. /*
  28. 获取运行时类的父类
  29. */
  30. @Test
  31. public void test2() {
  32. Class<? extends Person> clazz = new Person().getClass();
  33. Class<?> superclass = clazz.getSuperclass();
  34. System.out.println(superclass);
  35. }
  36. /*
  37. 获取运行时类的带泛型的父类
  38. */
  39. @Test
  40. public void test3() throws ClassNotFoundException {
  41. Class<?> clazz = Class.forName("com.atguigu.java2.Person");
  42. Type superclass = clazz.getGenericSuperclass();
  43. System.out.println(superclass);
  44. }
  45. /*
  46. 获取运行时类的带泛型的父类的泛型
  47. 代码: 逻辑性代码 vs 功能性代码
  48. */
  49. @Test
  50. public void test4() throws ClassNotFoundException {
  51. Class<?> clazz = Class.forName("com.atguigu.java2.Person");
  52. Type genericSuperclass = clazz.getGenericSuperclass();
  53. ParameterizedType parameterizedType= (ParameterizedType) genericSuperclass;
  54. Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
  55. System.out.println(actualTypeArguments[0].getTypeName());
  56. }
  57. /*
  58. 获取运行时类实现的接口
  59. */
  60. @Test
  61. public void test5(){
  62. Class<Person> clazz = Person.class;
  63. Class<?>[] interfaces = clazz.getInterfaces();
  64. for (Class c:interfaces){
  65. System.out.println(c);
  66. }
  67. System.out.println();
  68. //获取运行时类的父类的接口
  69. Class<?>[] interfaces1 = clazz.getSuperclass().getInterfaces();
  70. for (Class c:interfaces1){
  71. System.out.println(c);
  72. }
  73. }
  74. /*
  75. 获取运行时类所在的包
  76. */
  77. @Test
  78. public void test6(){
  79. Class<Person> clazz = Person.class;
  80. Package pack = clazz.getPackage();
  81. System.out.println(pack);
  82. }
  83. /*
  84. 获取运行时类声明的注解
  85. */
  86. @Test
  87. public void test7(){
  88. Class<Person> clazz = Person.class;
  89. Annotation[] annotations = clazz.getAnnotations();
  90. for (Annotation a:annotations){
  91. System.out.println(a);
  92. }
  93. }
  94. }

7、调用运行时类的指定结构

  1. package com.atguigu.java3;
  2. import com.atguigu.java2.Person;
  3. import org.junit.Test;
  4. import java.lang.reflect.Constructor;
  5. import java.lang.reflect.Field;
  6. import java.lang.reflect.InvocationTargetException;
  7. import java.lang.reflect.Method;
  8. /*
  9. 调用运行时类中指定的结构:属性、方法、构造器
  10. */
  11. public class ReflectionTest {
  12. @Test
  13. public void test1() throws NoSuchFieldException, InstantiationException, IllegalAccessException {
  14. Class clazz = Person.class;
  15. //创建运行时类的对象
  16. Person p = (Person) clazz.newInstance();
  17. //获取指定的属性:要求运行时类中的属性声明为public
  18. //通常不采用此方法
  19. Field id = clazz.getField("id");
  20. /*
  21. 设置当前属性的值
  22. set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少
  23. */
  24. id.set(p, 1001);
  25. /*
  26. 获取当前属性的值
  27. get():参数1:获取哪个对象的当前属性值
  28. */
  29. int pId = (int) id.get(p);
  30. System.out.println(pId);
  31. }
  32. /*
  33. 如何操作运行时类中的指定的属性---需要掌握
  34. */
  35. @Test
  36. public void test2() throws Exception {
  37. Class<Person> clazz = Person.class;
  38. //创建运行时类的对象
  39. Person p = clazz.newInstance();
  40. //1、getDeclaredField(String name) :获取当前运行时类中指定变量名的属性。
  41. Field name = clazz.getDeclaredField("name");
  42. //2、保证当前属性是可访问的
  43. name.setAccessible(true);
  44. //3、获取、设置指定对象的此属性值
  45. name.set(p,"Tom");
  46. System.out.println(name.get(p));
  47. }
  48. /*
  49. 如何操作运行时类中的指定的方法---需要掌握
  50. */
  51. @Test
  52. public void test3() throws Exception {
  53. Class<Person> clazz = Person.class;
  54. //创建运行时类的对象
  55. Person p = clazz.newInstance();
  56. //1、获取指定的某个方法getDeclaredMethod():参数1:指明获取的方法的名称 参数2:指明获取的方法的形参列表
  57. Method show = clazz.getDeclaredMethod("show", String.class);
  58. //2、保证当前方法是可访问的
  59. show.setAccessible(true);
  60. /*
  61. 3、调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参
  62. invoke()的返回值即为对应类中调用的方法的返回值。
  63. */
  64. Object returnValue = show.invoke(p, "CHN");
  65. System.out.println(returnValue);
  66. System.out.println("*******************静态方法******************");
  67. Method showDesc = clazz.getDeclaredMethod("showDesc");
  68. showDesc.setAccessible(true);
  69. //如果调用的运行时类中的方法没有返回值,则此invoke()返回null
  70. Object returnVal = showDesc.invoke(Person.class);
  71. System.out.println(returnVal);
  72. }
  73. /*
  74. 如何操作运行时类中的指定的构造器
  75. */
  76. @Test
  77. public void test4() throws Exception {
  78. Class<Person> clazz = Person.class;
  79. //1、获取指定的构造器getDeclaredConstructor():参数:指明构造器的参数列表
  80. Constructor<Person> constructor = clazz.getDeclaredConstructor(String.class);
  81. //2、保证此构造器是可访问的
  82. constructor.setAccessible(true);
  83. //3、调用此构造器创建运行时类的对象
  84. Person p = constructor.newInstance("Tom");
  85. System.out.println(p);
  86. }
  87. }

尚硅谷宋红康第15章_Java反射机制.pdf