ClassLoader与System学习笔记

    类加载器

/**
 * 类加载器负载加载类对象、资源
 * 一般策略是将给定名称转为文件名,然后从文件系统中进行加载
 * 类加载器采用委托机制进行加载类和资源-->在加载类或者资源之前将操作委托给父加载器进行加载
 * @author Administrator
 *
 */

测试代码

package com.undergrowth.lang;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.net.URL;

import org.junit.Test;

/**
 * 类加载器负载加载类对象、资源
 * 一般策略是将给定名称转为文件名,然后从文件系统中进行加载
 * 类加载器采用委托机制进行加载类和资源-->在加载类或者资源之前将操作委托给父加载器进行加载
 * @author Administrator
 *
 */
public class ClassLoaderLearn {

	public ClassLoaderLearn() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 获取系统的类加载器及其父类
	 */
	@Test
	public void testClassLoaderName(){
		ClassLoader classLoader=ClassLoader.getSystemClassLoader();
		iteratorClassLoader(classLoader);
	}

	/**
	 * 迭代类加载器
	 * @param classLoader
	 */
	private void iteratorClassLoader(ClassLoader classLoader) {
		while(classLoader!=null){
			System.out.println(classLoader);
			classLoader=classLoader.getParent();
		}
	}
	
	/**
	 * 显示加载资源的URL
	 * @throws IOException
	 * @throws URISyntaxException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	@Test
	public void testLoadResource() throws IOException, URISyntaxException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		URL url=ClassLoader.getSystemResource("resources"+System.getProperty("file.separator")+"config.xml");
		System.out.println("==================显示文件资源==================");
		disUrl(url);
		System.out.println("==================显示网络资源==================");
		url=new URL("http://dict.youdao.com/search?le=eng&q=%E9%80%92%E5%BD%92&keyfrom=dict.top");
		disUrl(url);
		
	}

	/**
	 * 利用反射获取方法名进行 显示
	 * 显示资源定位符的信息
	 * @param url
	 * @throws IOException
	 * @throws URISyntaxException
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 */
	private void disUrl(URL url) throws IOException, URISyntaxException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub
		Method[] methods=url.getClass().getDeclaredMethods();
		for (Method method : methods) {
			//只获取不带参数的方法
			if(method.getParameterTypes().length==0)
			System.out.println(method.getName()+"-->"+method.invoke(url, null));
		}
		/*System.out.println("url.getFile():"+url.getFile());
		System.out.println("url.getAuthority():"+url.getAuthority());
		System.out.println("url.getContent():"+url.getContent());
		System.out.println(":"+url.getDefaultPort());
		System.out.println(":"+url.getHost());
		System.out.println(":"+url.getPath());
		System.out.println(":"+url.getPort());
		System.out.println(":"+url.getProtocol());
		System.out.println(":"+url.getQuery());
		System.out.println(":"+url.getRef());
		System.out.println(":"+url.getUserInfo());
		System.out.println(":"+url.hashCode());
		System.out.println(":"+url.openConnection());
		System.out.println(":"+url.openStream());
		System.out.println(":"+url.toExternalForm());
		System.out.println("url.toString():"+url.toString());
		System.out.println("url.toURI():"+url.toURI());*/
	}
	
	/**
	 * 显示加载输入流资源 进行读取
	 * @throws IOException
	 */
	@Test
	public void testLoadInputStream() throws IOException{
		System.out.println("==================加载输入流资源==================");
		InputStream is=ClassLoader.getSystemResourceAsStream("resources"+System.getProperty("file.separator")+"config.xml");
		BufferedReader reader=new BufferedReader(new InputStreamReader(is));
		//byte[] num=new byte[1024];
		int n=0;
		System.out.println(is.markSupported());
		//进行流标记
		is.mark(0);
		while ((n=is.read())!=-1) {
			System.out.print((char)n);
		}
		System.out.println();
		//重置流 重新读取
		is.reset();
		String content=null;
		while ((content=reader.readLine())!=null) {
			System.out.println(content);
		}
	}
	
	/**
	 * 自定义类加载器
	 * @author Administrator
	 *
	 */
	class CustomerClassLoader extends ClassLoader{

		/**
		 * 父类的实现默认为抛出MathLearn异常
		 * 将父类的protected修饰符扩大 改为public 供外部使用
		 */
		@Override
		public Class<?> findClass(String name) throws ClassNotFoundException {
			// TODO Auto-generated method stub
			Class<?> class1=null;
			InputStream is=null;
			try {
				//获取类的字节码文件
				is = ClassLoader.getSystemResourceAsStream(name.replace(".", System.getProperty("file.separator"))+".class");
				byte[] b=new byte[is.available()];
				//读取到字节数组中
				is.read(b);
				//转换为相应的字节码
				class1=defineClass(name, b, 0,b.length);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return class1;
		}
		
		/**
		 * 扩大修饰符 供外部使用
		 */
		@Override
		public Package getPackage(String name) {
			// TODO Auto-generated method stub
			return super.getPackage(name);
		}

		/**
		 * 扩大修饰符 供外部使用
		 */
		@Override
		public Package[] getPackages() {
			// TODO Auto-generated method stub
			return super.getPackages();
		}
		
		
		
	}
	
	/**
	 * 测试自定义类加载器
	 * 类加载器采用委托机制 进行加载类
	 * @throws ClassNotFoundException
	 */
	@Test
	public void testCustomClassLoader() throws ClassNotFoundException{
		CustomerClassLoader classLoader=new CustomerClassLoader();
		//迭代类加载器
		iteratorClassLoader(classLoader);
		//加载类 MathLearn
		@SuppressWarnings("unchecked")
		Class<MathLearn> mathLearn=(Class<MathLearn>) classLoader.loadClass("com.undergrowth.lang.MathLearn");
		System.out.println("mathLearn的类加载器为:"+mathLearn.getClassLoader());
		iteratorClassMethod(mathLearn);
	}
   
	/**
	 * 迭代类字节码方法
	 * @param mathLearn
	 */
	private void iteratorClassMethod(Class<MathLearn> mathLearn) {
		for(Method method:mathLearn.getDeclaredMethods()){
			System.out.println(method.getName());
		}
	}
	
	/**
	 * 查找类加载器
	 * @throws ClassNotFoundException
	 */
	@Test
	public void testFindClass() throws ClassNotFoundException {
		CustomerClassLoader classLoader=new CustomerClassLoader();
		// 查找类 MathLearn
		@SuppressWarnings("unchecked")
		Class<MathLearn> mathLearn = (Class<MathLearn>) classLoader
				.findClass("com.undergrowth.lang.MathLearn");
		iteratorClassMethod(mathLearn);
	}
	
	/*
	 * 查找包相关信息
	 */
	@Test
	public void testPackage() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		CustomerClassLoader classLoader=new CustomerClassLoader();
		Package package1=classLoader.getPackage("com.undergrowth.lang");
		disPackageMethod(package1);
	}

	/**
	 * 显示包相关信息
	 * @param package1
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 */
	private void disPackageMethod(Package package1) {
		// TODO Auto-generated method stub
		Method[] methods = package1.getClass().getDeclaredMethods();
		for (Method method : methods) {
			// 只获取不带参数的方法
			if (method.getParameterTypes().length == 0)
				try {
					// 调用实例方法
					System.out.println(method.getName() + "-->"
							+ method.invoke(package1, null));
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
		}
	}
	
	
}


System

/**
 * 标准输入、输出、错误流 
 * 环境信息访问、设置、系统属性
 * 加载文件和类库 
 * 复制数组方法、调用垃圾回收器、java虚拟机、信道、安全管理器
 * 
 * @author Administrator
 * 
 */

测试代码

package com.undergrowth.lang;

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.channels.Channel;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;

/**
 * 标准输入、输出、错误流 
 * 环境信息访问、设置、系统属性
 * 加载文件和类库 
 * 复制数组方法、调用垃圾回收器、java虚拟机、信道、安全管理器
 * 
 * @author Administrator
 * 
 */
public class SystemLearn {

	public SystemLearn() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 测试标准输入流
	 * 
	 * @throws IOException
	 */
	@Test
	public void testIn() throws IOException {
		// 将字节流传唤为字符流 进行操作
		BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
		String n = null;
		while ((n = is.readLine()) != null && !"".equals(n)) {
			System.out.format("%s %d", n, n.length());
		}
	}

	/**
	 * 测试标准输出流
	 */
	@Test
	public void testOut() {
		PrintStream ps = System.out;
		ps.append("你好啊,System.out\n");
		ps.println("换行符");
		ps.format("%s %n", "你好啊", "你好啊".length());
		ps.write(20);
		ps.flush();
		ps.close();
	}

	/**
	 * 测试标准错误流
	 */
	@Test
	public void testErr() {
		PrintStream ps = System.err;
		ps.append("你好啊,System.out\n");
		ps.println("换行符");
		ps.format("%s %n", "你好啊", "你好啊".length());
		ps.write(20);
		ps.flush();
		ps.close();
	}

	/**
	 * 测试获取环境信息、系统属性、系统时间
	 */
	@Test
	public void testEnvironmentGet() {
		// 获取当前时间 毫秒数
		System.out.println(System.currentTimeMillis() + "\t"
				+ new Date(System.currentTimeMillis())+"\t"+System.nanoTime());
		// 获取当前环境信息的Map映射视图
		for (Map.Entry<String, String> env : System.getenv().entrySet()) {
			System.out.println(env.getKey() + ":" + env.getValue());
		}
		System.out.println("====================================");
		//获取系统属性
		Properties properties=System.getProperties();
		properties.list(System.out);
		//Set遍历
		System.out.println("====================================");
		for(String propertyName:properties.stringPropertyNames()){
			//移除系统指定属性
			if("sun.desktop".equals(propertyName)) System.out.println(System.clearProperty(propertyName));
			System.out.println(propertyName+"-->"+properties.getProperty(propertyName));
		}
	}

	/**
	 * 关于垃圾回收器、java虚拟机、hashcode
	 */
	@Test
	public void testOther(){
		
		//返回指定对象的哈希值
		System.out.println(System.identityHashCode("123454"));
		
		//运行处于挂起状态的终止方法 
		System.runFinalization();
		
		//垃圾回收
		System.out.println("调用垃圾回收机制进行清理所丢弃的对象,但是垃圾回收机制的线程级别很低,不能保证马上执行");
		System.gc();
		Runtime.getRuntime().gc();
		
		
		//终止虚拟机退出 非0为异常终止
		System.out.println("java虚拟机推出之前,显示");
		System.exit(0);
		Runtime.getRuntime().exit(0);
		System.exit(1);
		Runtime.getRuntime().exit(1);
		System.out.println("java虚拟机已终止,不会显示了");
	}
	
	/**
	 * 测试控制台
	 */
	@Test
	public void testConsole() {
		// 如果没有重新定向输入、输出 则有控制台
		// 但是eclipse已经重定向了 所以下面代码不会执行
		// 获取控制台
		Console console = System.console();
		char[] pass = null;
		if (console != null) {
			pass = console.readPassword("[%s]", "请输入密码");
			System.out.println(pass);
			Arrays.fill(pass, ' ');
			System.out.println(pass);
		}
	}
	
	/**
	 * 获取安全属性
	 */
	@Test
	public void getSecurityManager(){
		SecurityManager securityManager=System.getSecurityManager();
		if (securityManager!=null) {
			System.out.println(securityManager);
		}
	}

	/**
	 * 获取信道
	 * @throws IOException 
	 */
	@Test
	public void getChannel() throws IOException{
		Channel channel=System.inheritedChannel();
		if(channel!=null)
			System.out.println(channel.isOpen());
	}
	
	/**
	 * 测试复制数组
	 */
	@Test
	public void testArray(){
		char[] src=new char[1024];
		Arrays.fill(src, (char)49);
		System.out.println(Arrays.toString(src));
		char[] dest=new char[512];
		System.arraycopy(src, 0, dest, 0, dest.length);
		System.out.println(Arrays.toString(dest));
	}
	
	/**
	 * 加载静态库
	 * 对于window而言 是加载dll 动态链接库
	 * 对于unix/linux而言 是加载静态共享库文件 .so
	 * 加载静态共享库后 可通过jni技术 调用本地方法(c/c++)
	 * 在嵌入式领域中 驱动开发中 当需要底层驱动与上层应用交互时 即会经常使用
	 */
	@Test
	public void testLoad(){
		System.loadLibrary("");
		Runtime.getRuntime().loadLibrary("");
		System.load("");
		Runtime.getRuntime().load("");
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值