newCreating objectsisstaticLoading classes requires loading all classes that may be used at compile time.
One hundred classes, one of which is wrong, cannot be compiled.
This problem can be solved by dynamically loading classes
By dynamically compiling the Class class
and then calling the instance to complete the dynamic compilation
1 public class OfficeBetter { 2 3 public static void main(String[] args) throws InstantiationException, IllegalAccessException { 4 try { 5 //动态加载类,在运行时刻加载 6 Class c =Class.forName(args[0]); 7 //通过类类型,创建该类对象 8 OfficeAble oa =(OfficeAble)c.newInstance(); 9 oa.start();10 } catch (ClassNotFoundException e) {11 e.printStackTrace();12 }13 14 } 15 16 }
An interface is used to facilitate word, it is also convenient for excel to be implemented using
1 public interface OfficeAble {2 public void start();3 }
1 public class Word implements OfficeAble{2 3 public void start() {4 System.out.println("word....starts...");5 }6 7 }
The above is the detailed content of Dynamic compilation of Java. For more information, please follow other related articles on the PHP Chinese website!