JAVA基础--类加载器和代理总结

类加载器的概念:

类加载器就是加载类的工具,JVM在运行的时候需要加载类的class文件进内存,生成类的字节码文件。加载class文件并生成类的字节码文件的过程就是由类加载器来完成的。


因为类加载器本身也是java类,而任何的java类都需要被加载器加载,所以必然会有一个类加载器不是java类,它就是Bootstrap。JVM中还内置了两个类加载器:ExtClassLoader和AppClassLoader,它们由Bootstrap加载。

Bootstrap加载:jre/lib/rt.jar

ExtClassLoader加载:jre/lib/ext/*.jar

AppClassLoader加载classPath下的所有jar或者目录


它们之间的关系和负责加载范围见此图:



类加载器的委托机制:

当Java虚拟机要加载一个类时,到底派出哪个类加载器去加载呢?
1.首先当前线程的类加载器去加载线程中的第一个类。
2.如果类A中引用了类B,Java虚拟机将使用加载类A的类装载器来加载类B。 
3.还可以直接调用ClassLoader.loadClass()方法来指定某个类加载器去加载某个类。

在每个类加载器加载类时,会先委托给其上级类加载器。
当所有上级类加载器没有加载到类,会回到发起者类加载器,发起者加载器还加载不了,则抛ClassNotFoundException。

相同的class打成jar包,分别放到jre/lib/ext和classPath下,会加载ext下的,因为父类委托机制父类加载到就直接返回了。


自定义类加载器:

原理:

继承ClassLoader为了保留原来的委托机制,不覆盖loadClass方法,直接继承自父类。只需要覆盖findClass方法,此方法中使用defineClass方法返回一个class。

实现步骤:

对ClassLoaderAttachment.class文件进行加密,加密结果存放到另外一个目录ClassLoaderlib文件夹下,需要用自定义的类加载器才能加载。


//创建一个类用于测试

package ClassLoader;
import java.util.Date;
public class ClassLoaderAttachment extends Date {
	public String toString(){
		return "hello itcast";
	}
}

自定义类加载器,加密结果存放到ClassLoaderlib文件夹

package ClassLoader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MyClassLoad extends ClassLoader{
	public static void main(String[] args) throws Exception {
		String srcPath = args[0];
		String destDir = args[1];
		InputStream fis = new FileInputStream(srcPath);
		String destFileName = srcPath.substring(srcPath.lastIndexOf('\\')+1);
		String destPath = destDir + "\\" + destFileName;
		OutputStream fos = new FileOutputStream(destPath);
		cypher(fis,fos);
		fis.close();
		fos.close();
	}
	private static void cypher(InputStream ips,OutputStream ops) throws IOException{
		int b = -1;
		while((b=ips.read())!=-1){
			ops.write(b ^ 0xff);
		}
	}
	private String classDir;
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		String fileName = classDir + "\\" + name.substring(name.lastIndexOf('.')+1) + ".class";
		try {
			InputStream fis = new FileInputStream(fileName);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			cypher(fis, bos);
			byte[] bytes = bos.toByteArray();
			return defineClass(bytes, 0, bytes.length);
		} catch (Exception e) {
		}
		return super.findClass(name);
	}
	public MyClassLoad(){
		
	}
	public MyClassLoad(String classDir){
		this.classDir = classDir;
	}
}

对类加载器进行测试:

package ClassLoader;
import java.util.Date;
public class ClassLoadText {
	public static void main(String[] args) throws Exception {
		System.out.println(loader);
//		System.out.println(new ClassLoaderAttachment().toString());//这里会报错,必须由自定义的来加载
		Class myLoader = new MyClassLoad("ClassLoaderlib").loadClass("ClassLoader.ClassLoaderAttachment");
//		ClassLoaderAttachment cla = myLoader.newInstance();
		Date d1 = (Date)myLoader.newInstance();
		System.out.println(d1);
	}
}

=======================================================================================

代理


面向方面编程(AOP):

系统中可能存在交叉业务,一个交叉业务就是要切入到系统中的一个方面,如下所示:
                                   安全       事务         日志
StudentService ------|----------|------------|-------------
CourseService ------|----------|------------|-------------
MiscService ------|----------|------------|-------------
AOP(Aspect oriented program ),面向方面的编程的目标就是要使交叉业务模块化。可以采用将切面代码移动到原始方法的周围,这与直接在方法中编写切面代码的运行效果是一样的,如下所示:
------------------------------------------------------切面
func1         func2            func3
{             {                { 
....            ....              ......
}             }                }
------------------------------------------------------切面
使用代理技术正好可以解决这种问题,代理是实现AOP功能的核心和关键技术。


代理:应用程序出了当前类能提供的功能外,有时需要一些其他的额外功能,比如安全、日志等,这时需要用代理类。


Proxy类和InvacationHandler接口提供了生成动态代理的功能。

1.getProxyClass()方法:创建动态代理类的字节码。

Proxy.getProxyClass(loader, interfaces):接收两个参数,loader指定动态代理类的类加载器,interfaces指定动态代理类要实现的接口。返回Class对象。

2.newProxyInstance()方法:创建动态代理类的示例。

Proxy.newProxyInstance(loader, interfaces, h):接收三个参数,loader指定动态代理类的类加载器,interfaces指定动态代理类要实现的接口,h指定 与动态代理类关联的InvacationHandler对象。

代码示例:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyDemo {
	public static void main(String[] args) {
		Collection proxy3 = (Collection)Proxy.newProxyInstance(
				Collection.class.getClassLoader(),
				new Class[]{Collection.class},
				new InvocationHandler() {
					ArrayList target = new ArrayList();
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						long beginTime = System.currentTimeMillis();
						Object retVal = method.invoke(target, args);
						long endTime = System.currentTimeMillis();
						System.out.println(method.getName()+" runing time of "+(endTime-beginTime));
						return retVal;
					}
				}
				);
		proxy3.add("zxx");
		proxy3.add("lhm");
		proxy3.add("bxd");
		System.out.println(proxy3.size());
	}

}

JVM生成的动态类必须实现一个或多个接口,所以,JVM生成的动态类只能用作具有相同接口的目标类的代理。
CGLIB库可以动态生成一个类的子类,一个类的子类也可以用作该类的代理,所以,如果要为一个没有实现接口的类生成动态代理类,那么可以使用CGLIB库。


Proxy类中继承自Object的方法中,只有equalstoStringhashCode方法交给InvocationHandler处理,剩余的其他方法会调用Proxy自己的方法

代理类的各个方法中通常除了要调用目标的相应方法和对外返回目标返回的结果外,还可以在代理方法中的如下四个位置加上系统功能代码:
1.在调用目标方法之前
2.在调用目标方法之后
3.在调用目标方法前后
4.在处理目标方法异常的catch块中


动态代理的工作原理:当调用代理的各个方法时,会把请求传递给由代理类传递进来的InvacationHandler对象。InvacationHandler对象通过invoke()方法把请求分给目标对象的各个方法。


为了让代码更加的灵活,需要将目标类传入代理的Invoke方法中,需要target和系统代码封装成对象,抽到InvocationHandler外面,之后通过参数的方法传递进去。getProxytarketadvice

代码示例:

import java.lang.reflect.Method;

public interface Advice {
	
	void beforeMethod(Method method);
	void afterMethod(Method method);
	
}

import java.lang.reflect.Method;

public class MyAdvice implements Advice{
	long beginTime;

	public void beforeMethod(Method method) {
		System.out.println("附加功能1");
		beginTime = System.currentTimeMillis();
	}

	public void afterMethod(Method method) {
		System.out.println("附加功能");
		long endTime = System.currentTimeMillis();
		System.out.println(method.getName()+" runing time of "+(endTime-beginTime));
	}
}

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyDemo {
	public static void main(String[] args) {
		final ArrayList target = new ArrayList();//将目标抽出	
		Collection proxy = (Collection)getProxy(target,new MyAdvice());
		proxy.add("zxx");
		proxy.add("lhm");
		proxy.add("bxd");
		System.out.println(proxy.size());
	}

	private static Object getProxy(final Object target , final Advice advice) {
		Object proxy = Proxy.newProxyInstance(
				target.getClass().getClassLoader(),
//				new Class[]{Collection.class},
				target.getClass().getInterfaces(),
				new InvocationHandler() {
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						
						advice.beforeMethod(method);
						Object retVal = method.invoke(target, args);
						advice.afterMethod(method);
						
						return retVal;
					}
				}
				);
		return proxy;
	}

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值