1. The difference between dynamically loaded classes and statically loaded classes in Java
The way new creates objects is called static loading, and using Class.forName(" XXX") is called dynamic loading. The essential difference between them is that the source program of a statically loaded class is loaded during compilation (must exist), while the source program of a dynamically loaded class can be absent during compilation (the source program does not need to exist).
2. Why is it necessary to dynamically load classes
From my own understanding, dynamically loading classes increases the flexibility of the program. For example, there are 50 functions in a program, but you may only use one of them. If you use static loading, you must provide all the definitions of 100 functions before compilation, otherwise the compilation will not pass. If you use It is a dynamic loading mechanism, so there is no need to spend so much time, just define which one to use.
Static loading:
public class Office_Static { public static void main(String[] args) { //new 创建对象,是静态加载类,在编译时刻就需要加载所有的可能使用到的类 if("Word".equals(args[0])){ Word w = new Word(); w.start(); } if("Excel".equals(args[0])){ Excel e = new Excel(); e.start(); } } }
The two classes Word and Excel must exist when compiling this program. Even if Excel is not used after judgment, it must be loaded
Dynamic loading:
1. Interface OfficeAble:
public interface OfficeAble { public void start(); }
2. Word implementation interface:
public class Word implements OfficeAble{ public void start(){ System.out.println("word start"); } }
3. Excel implementation interface:
public class Excel implements OfficeAble{ public void start(){ System.out.println("excel start"); } }
4. Main method
public class OfficeBetter { public static void main(String[] args) { try { //动态加载类,在运行时刻加载 Class c = Class.forName(args[0]);//在运行配置里面输入加载类.Excel //通过类类型,创建该类对象(先转换为Word和Excel的共同接口OfficeAble) OfficeAble oa = (OfficeAble)c.newInstance(); oa.start(); //不推荐下面两种,因为不确定是加载Word还是Excel,要强转 // Word word = (Word)c.newInstance(); // word.start(); // Excel excel = (Excel)c.newInstance(); // excel.start(); } catch (Exception e) { e.printStackTrace(); } } }
The above is the detailed content of Detailed explanation of how Java implements reflective static loading and dynamic loading of example code. For more information, please follow other related articles on the PHP Chinese website!