image.png
    image.png
    image.png
    image.png
    image.png

    1. package com.atguigu.java;
    2. import org.junit.Test;
    3. import java.lang.reflect.Constructor;
    4. import java.lang.reflect.Field;
    5. import java.lang.reflect.InvocationTargetException;
    6. import java.lang.reflect.Method;
    7. /**
    8. * @author Dxkstart
    9. * @create 2021-11-23-18:15
    10. */
    11. public class ReflectionTest {
    12. //反射之后
    13. @Test
    14. public void test1() throws Exception {
    15. Class<Person> clazz = Person.class;
    16. //1.通过反射,创建Person类的对象
    17. Constructor<Person> constructor = clazz.getConstructor(String.class, int.class);
    18. Person tom = constructor.newInstance("Tom", 12);
    19. System.out.println(tom.toString());
    20. //2.通过反射,调用对象指定的属性、方法
    21. //调用属性
    22. Field age = clazz.getDeclaredField("age");
    23. age.set(tom,10);
    24. System.out.println(tom.toString());
    25. //调用方法
    26. Method show = clazz.getDeclaredMethod("show");
    27. show.invoke(tom);
    28. System.out.println("************************");
    29. //通过反射,可以调用Person类额私有结构的,比如:私有构造器,方法,属性
    30. //私有构造器
    31. Constructor<Person> con1 = clazz.getDeclaredConstructor(String.class);
    32. con1.setAccessible(true);
    33. Person jerry = con1.newInstance("Jerry");
    34. System.out.println(jerry);
    35. //私有属性
    36. Field name = clazz.getDeclaredField("name");
    37. name.setAccessible(true);
    38. name.set(jerry,"Mack");
    39. System.out.println(jerry);
    40. //私有方法
    41. Method showNation = clazz.getDeclaredMethod("showNation", String.class);
    42. showNation.setAccessible(true);
    43. String nation = (String) showNation.invoke(jerry,"china");
    44. System.out.println(nation);
    45. }
    46. }