1. package com.atguigu.java1;
    2. import org.junit.Test;
    3. import java.util.Random;
    4. /**
    5. * 通过反射创建对应的运行时类的对象
    6. *
    7. * @author Dxkstart
    8. * @create 2021-06-07 12:48
    9. */
    10. public class NewInstanceTest {
    11. @Test
    12. public void test1() throws IllegalAccessException, InstantiationException {
    13. Class<Person> clazz = Person.class;
    14. /*
    15. newInstance():调用此方法,创建对于的运行时类的对象。内部调用了运行时类的空参构造器。
    16. 要想此方法正常的创建运行时类的对象,要求:
    17. 1.运行时类必须提供空参的构造器
    18. 2.空参的构造器的访问权限得够。通常,设置为public。
    19. 在Javabean中要求提供一个public的空参构造器。原因:
    20. 1.便于通过反射,创建运行时类的对象
    21. 2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
    22. */
    23. Person p1 = clazz.newInstance();
    24. System.out.println(p1);
    25. }
    26. //体会反射的动态性
    27. @Test
    28. public void test2() {
    29. for (int i = 0; i < 100; i++) {
    30. int num = new Random().nextInt(3);//0,1,2
    31. String classPath = "";
    32. switch (num){
    33. case 0:
    34. classPath = "java.util.Date";
    35. break;
    36. case 1:
    37. classPath = "java.lang.Object";
    38. break;
    39. case 2:
    40. classPath = "com.atguigu.java1.Person";
    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. }