1、举例体会反射的动态性

  1. import org.junit.Test;
  2. import java.util.Random;
  3. /**
  4. * 通过发射创建对应的运行时类的对象
  5. */
  6. public class NewInstanceTest {
  7. @Test
  8. public void test2(){
  9. for(int i = 0;i < 100;i++){
  10. int num = new Random().nextInt(3);//0,1,2
  11. String classPath = "";
  12. switch(num){
  13. case 0:
  14. classPath = "java.util.Date";
  15. break;
  16. case 1:
  17. classPath = "java.lang.Object";
  18. break;
  19. case 2:
  20. classPath = "www.java.Person";
  21. break;
  22. }
  23. try {
  24. Object obj = getInstance(classPath);
  25. System.out.println(obj);
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
  31. /**
  32. * 创建一个指定类的对象。
  33. * classPath:指定类的全类名
  34. *
  35. * @param classPath
  36. * @return
  37. * @throws Exception
  38. */
  39. public Object getInstance(String classPath) throws Exception {
  40. Class clazz = Class.forName(classPath);
  41. return clazz.newInstance();
  42. }
  43. }