有如下简化代码:
准备知识:
Student judy = new Student;
Class s1 = Student.class;
Class s2 = judy.getClass();
Class s3 = null;
s3 = Class.forName("com.Student");
这里s1, s2, s3都是类类型
new创建对象是静态加载类,在编译时刻就需要加载所有的可能用到的类。
动态加载类的例子:
1 // OfficeAble.java
2 interface OfficeAble {
3
4 public void start();
5 // System.out.println("Word...stats
6 }
2 interface OfficeAble {
3
4 public void start();
5 // System.out.println("Word...stats
6 }
1 // Word.java 2 class Word implements OfficeAble { 3 4 public void start() { 5 System.out.println("Word...starts..."); 6 } 7 8 }
1 // OfficeBetter.java 2 class OfficeBetter { 3 4 public static void main(String[] args){ 5 6 try { 7 Class cType = Class.forName(args[0]); //get class class type 8 OfficeAble oa = (OfficeAble)cType.newInstance(); 9 oa.start(); 10 11 } catch (Exception e) { 12 e.printStackTrace(); 13 } 14 } 15 }
可通过命令行执行OfficeBetter类,同时给予执行参数,参数为想动态加载的类的类名。
以上整理自慕课网的Java教学视频http://www.imooc.com/video/3725/0,在此感谢慕课网的老师!