反射学习(二)java动态加载类

一 什么是动态加载类 什么是静态加载类

    Class.forName 不仅表示类的类类型,还代表了动态加载类。编译时加载是静态加载类,

运行时加载是动态加载类。

请大家区分编译 运行。

二.为何要使用动态加载类

用记事本写了一个程序 并没有写A类和B类以及start方法 

public class office {
	public static void main(String[] args) {
		if ("word".equals(args[0])) {
			word w = new word();
			w.start();
		}
		if ("excel".equals(args[0])) {
			excel e = new excel();
			e.start();
		}
	}
}
在执行javac office.java时会报错,原因是word和excel类不存在。假设我们想要使用word功能,写了一个word类,但是由于excel的原因,word功能也不能使用。

我们会发现,我们并不一定用到word功能或excel功能,可是编译却不能通过。而在日常的项目中,如果我们写了100个功能,因为一个功能的原因而导致所有功能不能使用,明显使我们不希望的。在这里,为什么会在编译时报错呢?new 是静态加载类,在编译时刻就需要加载所有可能使用到的功能。所以会报错。而在日常中我们希望用到哪个就加载哪个,不用不加载,就需要动态加载类。

使用动态加载类时,我们不用定义100种功能,只需要通过实现某种标准(实现某个接口)。

代码:

public interface officeInterface {
	public void start();
}
public class word implements officeInterface{
	@Override
	public void start() {
		System.out.println("word...start...");
	}
}
public class excel implements officeInterface{
	@Override
	public void start() {
		System.out.println("excel...start...");
	}
}
public class office{
	public static void main(String args[]){
		try{
			Class c=Class.forName(args[0]);
			officeInterface oi = (officeInterface) c.newInstance();
			oi.start();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}

这样的话,office类不需要再重新编译。新加功能的话只需要再写一个类实现officeInterface接口,例如PPT类,到时候只需要把PPT类重新编译一下,直接调用office类就可以实现特定的功能。这就是所谓的动态加载类。

猜你喜欢

转载自blog.csdn.net/lyj434786736lyj/article/details/81112237