java动态加载类和静态加载类笔记

时间:2021-01-14 08:22:55

JAVA中的静态加载类是编译时刻加载类  动态加载类指的是运行时刻加载类

二者有什么区别呢

举一个例子  现在我创建了一个类  实现的功能假设为通过传入的参数调用具体的类和方法

class office
{
public static void main(String args[])
{
if("word".equals(args[0])
{
word w=new word();
word.run();
}
if("excel".equals(args[0])
{
excel.run();
}
}
}

这个文件另存为office.java 很明显 这个类是无法编译通过的 运行javac office.java时  会报错无法找到类word 无法找到方法run 无法找到类excel  无法找到方法run

那我再新建一个文件word.java 功能为输出hello world number 1

class word
{
public void run(String args[])
{
System.out.println("hello world number 1")
}
}

这个时候我们再去编译office.java 就是会报错无法找到excel 和excel的run 方法

tips: new 创建对象 是静态加载类 在编译时刻就需要加载所有的可能使用到的类

如果说 我们就需要用到word的run 方法  excel的run方法我们暂时不会用到怎么办呢 在本例中word已经写好了 因为主程序无法编译却不能用 无疑这是每个程序员都不愿意看到的

考虑到实际开发过程中 我们写的方法肯定不会只有两种 假设 我们有一百种方法  但是其中有一个方法可能有问题 在我们的例子中就是excel 那么其他99种方法都不能用 因为无法编译通过 在实际项目中 这个肯定是无法接受的

这个时候 我们就需要用到类的动态加载 我们创建一个改善类 另存为officebetter.java

class officebetter
{
public static void main(String args[])
{
//动态加载类 在运行的时刻加载类
Class c=Class.forName(args[0]); }
}

这个时候 我们去编译这个文件

执行命令:javac officebetter.java 是不会报任何错误的

但是我们去运行的时候  传入一个参数excell 表示我们想加载excell 这个类

执行命令: java officebetter excell

就会报错无法找到excell这个类  再修改一下之前的类

class officebetter
{
public static void main(String args[])
{
//动态加载类 在运行的时刻加载类
Class c=Class.forName(args[0]);
//通过类类型 创建该类对象
word a=(word) c.newInstance();
a.run();
}
}

 我们执行 java officebetter word  就会发现 程序能够正常输出我们想要的字符串