JAVA-day12-IO3、反射

import java.io.*;
class Demo1
{
	public static void main(String[] args)throws IOException
	{
		/*
          PrintStream:打印流,具备字节输出流的基本功能,添加了打印功能
		  是一个可以向目的写入的输出流
		  目的:File
		        字符串形式的路径
				字节输出流

		*/

		PrintStream ps = new PrintStream("tt.txt");
        //一次写入一个字节
		//ps.write(353);//00000000 00000000 00000001 01100001  把低8位的一个字节写入

		ps.println(353);//按照数据原样儿写入,也就是数据的表现形式,内部使用了转成字符串的功能,String.valueOf()

		ps.write(String.valueOf(353).getBytes());

	}
}

import java.io.*;
class Demo2
{
	public static void main(String[] args) throws IOException
	{
		/*
         PrintWriter:字符打印流,字符输出流的基本功能都具备
		 目的:File
		       字符串形式的路径
			   字节输出流
			   字符数出流

		*/

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		//PrintWriter pw = new PrintWriter(System.out,true);

		PrintWriter pw2 = new PrintWriter(new FileWriter("t.txt"),true);

		String line = null;
		while((line = br.readLine())!=null)
		{
			if("over".equals(line))
				break;

			pw2.println(line);
			//pw.flush();

		}

	}
}
//序列流:SequenceInputStream
import java.io.*;
import java.util.*;
class  Demo3
{
	public static void main(String[] args) throws IOException
	{ /*
		FileInputStream fis1= new FileInputStream("Demo1.java");
		FileInputStream fis2= new FileInputStream("Demo2.java");
		FileInputStream fis3= new FileInputStream("Demo3.java");

		Vector<FileInputStream> v= new Vector<FileInputStream>();
		v.add(fis1);
		v.add(fis2);
		v.add(fis3);

		Enumeration<FileInputStream>  en = v.elements();*/

		ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();

        for(int i=1;i<=3;i++)
		{
			list.add(new FileInputStream("Demo"+i+".java"));
		}

		Enumeration<FileInputStream> en = Collections.enumeration(list);

		SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream("hebing2.java");

		byte[] b = new byte[1024];
		int len = 0;

		while((len = sis.read(b))!=-1)
		{
			fos.write(b,0,len);
		}

		sis.close();
		fos.close();

	}
}
//分割文件
import java.io.*;
import java.util.*;
class  Demo4
{
	public static void main(String[] args)throws IOException
	{
		File file = new File("C:\\Users\\qq\\Desktop\\ok.jpg");
		splitFile(file);
	}
    //分割文件
	public static void splitFile(File file)throws IOException
	{
	    if(!file.isFile())
		{
			System.out.println("不是文件");
			return;
		}

		//创建存储被分割出来的文件的目录
		File dir = new File("fenge");
		if(!dir.exists())
			dir.mkdir();

		FileInputStream fis = new FileInputStream(file);

		FileOutputStream fos = null;

        byte[] arr = new byte[1024*1024*2];
		int len = 0;
        int num = 1;
		while((len = fis.read(arr))!=-1)
		{
			fos = new FileOutputStream(new File(dir,(num++)+".suipian"));
			fos.write(arr,0,len);
		}

         //这几个被分割出来的文件上传之后,使用者不知道文件类型和一共有
		 //几个分割出的文件,应该把这些信息以配置文件的形式告诉使用者 

		 Properties pro = new Properties();

		 pro.setProperty("filetype",file.getName());
		 pro.setProperty("fileNumber",Integer.toString(--num));

         fos = new FileOutputStream(new File(dir,"config.properties"));

		 pro.store(fos," ");

	     fis.close();
		 fos.close();

	}
}
import java.io.*;
class Person implements Serializable//标记接口
{
	static final long serialVersionUID = 42L;

	private /*static*/ String name;//被静态修饰的成员不参与序列化
	private  /*transient*/ int age;  //瞬态的成员不参与序列化

	public Person(){}

	public Person(String name,int age)
	{
		this.name = name;
		this.age = age;
	}

	public String getName()
	{
		return this.name;
	}

	public int getAge()
	{
		return this.age;
	}

}
class  Demo5
{
	public static void main(String[] args)throws IOException,ClassNotFoundException
	{
		//writeObject();
        readObject();
	}
    //反序列化
	//对象是依赖于其所属的类的,有那个class才会有对象
	public static void readObject()throws IOException,ClassNotFoundException
	{
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj.txt"));

		Person person = (Person)ois.readObject();//5964614836505496678    -2747677651716560467

		System.out.println(person.getName()+","+person.getAge());
	}

	//写入对象
    //序列化:把一个对象写入到一个目的--对象的持久化
	public static void writeObject()throws IOException
	{
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.txt"));

		oos.writeObject(new Person("lisi",23));//5964614836505496678 Person.class

		oos.close();
	}
}
import java.io.*;
class Demo6
{
	public static void main(String[] args)throws IOException
	{
		/*
          RandomeAccessFile:
		     随机访问文件的流类
			 只能访问文件
			 内部既有字节输入流也有字节输出流
			 内部定义了一个字节数组,并通过指针操作该数组,所以能随机访问
		*/

		//writeFile();
        //readFile();
		rw();
	}

	public static void rw()throws IOException
	{
	    RandomAccessFile  raf = new RandomAccessFile("rw.txt","rw");

		raf.seek(30);
		raf.writeUTF("你好");

	    long index = raf.getFilePointer();

	    System.out.println("index="+index);

        raf.seek(30);
		String ss = raf.readUTF();
		System.out.println(ss);

	}
	public static void readFile()throws IOException
	{
		 RandomAccessFile  raf = new RandomAccessFile("temp.txt","r");
         byte[] arr = new byte[4];
		 int len = 0;
		 len = raf.read(arr);

		 int age = raf.readInt();
		 System.out.println(new String(arr,0,len)+","+age);

		 long index = raf.getFilePointer();

	     System.out.println("index="+index);

		 raf.seek(15);

		 len = raf.read(arr);
		 age = raf.readInt();

         System.out.println(new String(arr,0,len)+","+age);
	}

	public static void writeFile()throws IOException
	{
		//文件不存在会自动创建
	   RandomAccessFile  raf = new RandomAccessFile("temp.txt","rw");
	   raf.write("刘能".getBytes());
	   raf.writeInt(58);

	   long index = raf.getFilePointer();//得到指针指向的位置

	   raf.seek(15);

	   raf.write("赵四".getBytes());
	   raf.writeInt(56);

	   index = raf.getFilePointer();

	   System.out.println("index="+index);

	}
}
import java.io.*;
class  Demo7
{
	public static void main(String[] args)throws IOException
	{
		/*
		用于操作基本数据类型的流类
        DataInputStream  DataOutputStream

		*/

		writeData();
		readData();
	}

	public static void readData()throws IOException
	{
		DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));

		int a = dis.readInt();
		boolean boo = dis.readBoolean();
		double d = dis.readDouble();

		System.out.println(a+","+boo+","+d);
	}

	public static void writeData()throws IOException
	{
		DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));

		dos.writeInt(34);
		dos.writeBoolean(false);
		dos.writeDouble(45.56);

		dos.close();
	}
}
import java.io.*;
class  Demo8
{
	public static void main(String[] args)throws IOException
	{
		/*
         内存流:
		 ByteArrayInputStream:内部有一个字节数组
		 ByteArrayOutputStream: 内部有一个字节数组,直接写入了自己内部的字节数组了

        */

		ByteArrayInputStream du = new ByteArrayInputStream("owieurwoeir".getBytes());

		ByteArrayOutputStream xie = new ByteArrayOutputStream();

		byte[] arr = new byte[1024];
		int len = 0;

		while((len =du.read(arr))!=-1)
		{
			xie.write(arr,0,len);
		}

		System.out.println(new String(xie.toByteArray()));

	}
}
import java.io.*;
import java.util.*;
import java.text.*;
class Demo10
{
	public static void main(String[] args) throws IOException
	{
		try
		{
			int[] arr = new int[3];
			System.out.println(arr[3]);
		}
		catch (Exception e)
		{
			Date d = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss");
			String ss = sdf.format(d);

            PrintStream ps = new PrintStream("bug.txt");
			ps.println(ss);

            System.setOut(ps);
			e.printStackTrace(System.out);
		}

	}
}
/*
二:有五个学生,每个学生有3门课的成绩,
从键盘输入以上数据(包括姓名,三门课成绩),
输入的格式:如:zhagnsan,30,40,60计算出总成绩,
并把学生的信息和计算出的总分数高低顺序存放在磁盘文件"stud.txt"中。

1:描述一下学生
2:定义个操作学生的工具类
*/
import java.io.*;
import java.util.*;
class Student  implements Comparable<Student>
{
	private String name;
	private int math,china,eng;
	private int sum;

	public Student(){}

	public Student(String name,int math,int china,int eng)
	{
		this.name =name;
		this.math = math;
		this.china = china;
		this.eng = eng;
		sum = math+china+eng;
	}
	public int compareTo(Student stu)
	{
		int num = this.sum-stu.sum;
		return num==0?this.name.compareTo(stu.name):num;
	}
    public int getSum()
	{
        return this.sum;
    }
	public int getMath()
	{
	    return this.math;
	}
	public int getChina()
	{
		return this.china;
	}
	public int getEng()
	{
		return this.eng;
	}
    public String toString()
	{
	   return "Student["+name+","+math+","+china+","+eng+"]";
	}

}
//操作学生的工具类
class StuTool
{
	public static Set<Student> getStudents()
    {
	   return getStudents(null);
	}

	//读取键盘录入的学生信息,并存入集合
	public static Set<Student>  getStudents(Comparator<Student> com)throws IOException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		TreeSet<Student>   students;
		if(com!=null)
               students = new  TreeSet<Student>(com);
		else
               students = new  TreeSet<Student>();

		String line = null;
		for(int i=1;i<=3;i++)
		{
		   System.out.println("请输入第"+i+"个学员的信息");
		   line = br.readLine();
		   String[] arr = line.split(",");
		   Student stu = new Student(arr[0],Integer.parseInt(arr[1]),Integer.parseInt(arr[2]),Integer.parseInt(arr[3]));

           students.add(stu);
		}
		return students;

	}

	//把学员信息存入文件

	public static void saveToFile(Set<Student> students)throws IOException
	{
	     BufferedWriter  bw = new BufferedWriter(new FileWriter("stud.txt"));

		 for(Student stu:students)
		 {
		     bw.write(stu.toString()+"\t");
			 bw.write(""+stu.getSum());
			 bw.newLine();
			 bw.flush();
		 }

		 bw.close();
	}
}
class Demo11
{
	public static void main(String[] args) throws IOException
	{
		Comparator<Student>  com = Collections.reverseOrder();

		Set<Student>  s = StuTool.getStudents(com);

		StuTool.saveToFile(s);

	}
}
import  java.io.*;
class Demo12
{
	public static void main(String[] args)throws IOException
	{
		//转换流的编码问题
		//writeFile();
		readFile();
	}
    public static void readFile()throws IOException
	{
		InputStreamReader isr = new InputStreamReader(new FileInputStream("gbk.txt"),"utf-8");
		char[] ch = new char[10];
		int len = 0;
		len = isr.read(ch);
		System.out.println(new String(ch,0,len));
	}

	public static void writeFile()throws IOException
	{
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("utf.txt"),"utf-8");
		osw.write("你好");
		osw.close();

	}
}
/*
编码:家里有事,速回。----》电报文

	   byte[] getBytes()
          使用平台的默认字符集将此 String 编码为 byte 序列
	   byte[] getBytes(String charsetName)
          使用指定的字符集将此 String 编码为 byte 序列 

解码:电报文-----》家里有事,速回。
      String(byte[] bytes)
          通过使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
      String(byte[] bytes, Charset charset)
          通过使用指定的 charset 解码指定的 byte 数组,构造一个新的 String

编码编对了,解码就能解对
编码编错了,就不可能解对
*/
import java.util.*;
class  Demo13
{
	public static void main(String[] args)throws Exception
	{
		String ss ="你好";
		byte[] b = ss.getBytes("gbk");
		System.out.println(Arrays.toString(b));

        //解码解错了
		String str = new String(b,"ISO8859-1");
		System.out.println(str);

		//解决解码解错了的问题

       byte[] arr = str.getBytes("ISO8859-1");

       //使用gbk进行解码
	   String s = new String(arr);
	   System.out.println(s);

	}
}
class Demo14
{
	public static void main(String[] args)
	{
		String ss = "我的联通";

		byte[] b = ss.getBytes();

		for(byte num:b)
		{
			System.out.println(Integer.toBinaryString(num&255));
		}
	}
}
import java.io.*;
class Demo1
{
	public static void main(String[] args)throws IOException
	{
		/*
          PrintStream:打印流,具备字节输出流的基本功能,添加了打印功能
		  是一个可以向目的写入的输出流
		  目的:File
		        字符串形式的路径
				字节输出流

		*/

		PrintStream ps = new PrintStream("tt.txt");
        //一次写入一个字节
		//ps.write(353);//00000000 00000000 00000001 01100001  把低8位的一个字节写入

		ps.println(353);//按照数据原样儿写入,也就是数据的表现形式,内部使用了转成字符串的功能,String.valueOf()

		ps.write(String.valueOf(353).getBytes());

	}
}
import java.io.*;
class Demo2
{
	public static void main(String[] args) throws IOException
	{
		/*
         PrintWriter:字符打印流,字符输出流的基本功能都具备
		 目的:File
		       字符串形式的路径
			   字节输出流
			   字符数出流

		*/

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		//PrintWriter pw = new PrintWriter(System.out,true);

		PrintWriter pw2 = new PrintWriter(new FileWriter("t.txt"),true);

		String line = null;
		while((line = br.readLine())!=null)
		{
			if("over".equals(line))
				break;

			pw2.println(line);
			//pw.flush();

		}

	}
}
//序列流:SequenceInputStream
import java.io.*;
import java.util.*;
class  Demo3
{
	public static void main(String[] args) throws IOException
	{
		FileInputStream fis1= new FileInputStream("Demo1.java");
		FileInputStream fis2= new FileInputStream("Demo2.java");
		FileInputStream fis3= new FileInputStream("Demo3.java");

		Vector<FileInputStream> v= new Vector<FileInputStream>();
		v.add(fis1);
		v.add(fis2);
		v.add(fis3);

		Enumeration<FileInputStream>  en = v.elements();

		SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream("hebing.java");

		byte[] b = new byte[1024];
		int len = 0;

		while((len = sis.read(b))!=-1)
		{
			fos.write(b,0,len);
		}

		sis.close();
		fos.close();

	}
}
import java.io.*;
class Demo1
{
	public static void main(String[] args)throws IOException
	{
		/*
          PrintStream:打印流,具备字节输出流的基本功能,添加了打印功能
		  是一个可以向目的写入的输出流
		  目的:File
		        字符串形式的路径
				字节输出流

		*/

		PrintStream ps = new PrintStream("tt.txt");
        //一次写入一个字节
		//ps.write(353);//00000000 00000000 00000001 01100001  把低8位的一个字节写入

		ps.println(353);//按照数据原样儿写入,也就是数据的表现形式,内部使用了转成字符串的功能,String.valueOf()

		ps.write(String.valueOf(353).getBytes());

	}
}
import java.io.*;
class Demo2
{
	public static void main(String[] args) throws IOException
	{
		/*
         PrintWriter:字符打印流,字符输出流的基本功能都具备
		 目的:File
		       字符串形式的路径
			   字节输出流
			   字符数出流

		*/

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		//PrintWriter pw = new PrintWriter(System.out,true);

		PrintWriter pw2 = new PrintWriter(new FileWriter("t.txt"),true);

		String line = null;
		while((line = br.readLine())!=null)
		{
			if("over".equals(line))
				break;

			pw2.println(line);
			//pw.flush();

		}

	}
}
//序列流:SequenceInputStream
import java.io.*;
import java.util.*;
class  Demo3
{
	public static void main(String[] args) throws IOException
	{ /*
		FileInputStream fis1= new FileInputStream("Demo1.java");
		FileInputStream fis2= new FileInputStream("Demo2.java");
		FileInputStream fis3= new FileInputStream("Demo3.java");

		Vector<FileInputStream> v= new Vector<FileInputStream>();
		v.add(fis1);
		v.add(fis2);
		v.add(fis3);

		Enumeration<FileInputStream>  en = v.elements();*/

		ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();

        for(int i=1;i<=3;i++)
		{
			list.add(new FileInputStream("Demo"+i+".java"));
		}

		Enumeration<FileInputStream> en = Collections.enumeration(list);

		SequenceInputStream sis = new SequenceInputStream(en);

        FileOutputStream fos = new FileOutputStream("hebing2.java");

		byte[] b = new byte[1024];
		int len = 0;

		while((len = sis.read(b))!=-1)
		{
			fos.write(b,0,len);
		}

		sis.close();
		fos.close();

	}
}

反射

package com.qianfeng.reflect;

public class Demo1 {

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

	/**
	 *反射:动态获取类(class)及类中成员,并对类中的成员运行
	 *
	 *怎么获取到Class对象
	 *
	 *动态获取Person.class对象
	 *获取方式有三种:
	 *1:使用Object中的getClass()方法
	 *   需要先创建对象,所以的需要其所属的类实现存在
	 *:2:每个数据类型都有一个静态的属性class,通过该属性可以得到其所属的字节码文件对象
	 *    不需要创建对象了,但是需要那个类存在
	 * 3:Class.forName()只需要提供一个字符串,这个字符串的内容是类的名字
	 *
	 */
	public static void main(String[] args) throws ClassNotFoundException {

		//getClass1();
		//getClass2();
		getClass3();

	}

	private static void getClass3() throws ClassNotFoundException {
		Class claz = Class.forName("com.qianfeng.reflect.Person");

		System.out.println(claz);

	}

	private static void getClass2() {

		Class claz1 = Person.class;
		Class claz2 = Person.class;

		System.out.println(claz1==claz2);
	}

	private static void getClass1() {

		 Person p1 = new Person();
		 Class claz = p1.getClass();//Person.class

		 Person p2 = new Person();
		 Class claz2 = p2.getClass();//Person.class

		 System.out.println(claz==claz2);

	}
}
package com.qianfeng.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Demo2 {

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

	/**
	 * 动态获取类并创建对象
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 */
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {

         createObj1();
         createObj2();
	}
    //使用带参数的构造方法创建对象
	private static void createObj2() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//Person  p = new Person("lisi",23);
		Class claz = Class.forName("com.qianfeng.reflect.Person");

		Constructor cons = claz.getConstructor(String.class,int.class);

		Object obj = cons.newInstance("lili",23);

		System.out.println(obj);

	}

	private static void createObj1() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		//Person  p = new Person();

		Class claz = Class.forName("com.qianfeng.reflect.Person");//Person.class

		Object obj = claz.newInstance();//用的是默认的空参数的构造方法

		System.out.println(obj);

	}

}
package com.qianfeng.reflect;

import java.lang.reflect.Field;

public class Demo3 {

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

	/**
	 * 动态创建对象并给属性赋值
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {

        accessField1();
	}
   //动态创建对象并给属性赋值
	private static void accessField1() throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
		//Person p = new Person();
		//p.name = "";
		Class claz = Class.forName("com.qianfeng.reflect.Person");

		//Field field = claz.getField("name");//只能获取公共的成员属性
		Field field = claz.getDeclaredField("name");//只要是在类中的声明的就可以得到

		//创建一个Person类型的对象
		Object obj = claz.newInstance();

		//设置可以访问该属性---暴力访问
		field.setAccessible(true);

		field.set(obj, "zhangsan");

		System.out.println(obj);

	}
}
package com.qianfeng.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo4 {

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

	/**
	 * 动态执行类中的方法
	 * @throws ClassNotFoundException
	 * @throws SecurityException
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		invokeMethod1();
		invokeMethod2();
		invokeMethod3();

	}

    private static void invokeMethod3() throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    	Class claz = Class.forName("com.qianfeng.reflect.Person");

    	Method m = claz.getMethod("fun",null);

    	m.invoke(null,null);
	}

	private static void invokeMethod2() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    	Class claz = Class.forName("com.qianfeng.reflect.Person");

    	Method m = claz.getMethod("method", String.class);

    	//创建对象
    	Object obj = claz.newInstance();

    	m.invoke(obj, "haha");

	}

	//执行无参数的方法
	private static void invokeMethod1() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

		//Person p = new Person();
		//p.show();
		Class claz = Class.forName("com.qianfeng.reflect.Person");

		//得到方法
		Method   m = claz.getMethod("show",null);

		//创建对象
		Object obj = claz.newInstance();

		m.invoke(obj, null);
	}

}
时间: 2024-12-08 12:14:57

JAVA-day12-IO3、反射的相关文章

Java基础之反射

Java反射是指运行时获取类信息,进而在运行时动态构造对象.调用对象方法及修改对象属性的机制.百度百科的定义:“JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意方法和属性:这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制. 一.反射的用途 Java的反射机制可以做3件事:运行时创建对象.运行时调用方法.运行时读写属性.进而实现以下功能:调用一些私有方法,实现黑科技.比如双卡短信发送.设置状态栏颜色.自动挂电

第16篇-JAVA 类加载与反射

第16篇-JAVA 类加载与反射 每篇一句 :敢于弯曲,是为了更坚定的站立 初学心得: 追求远中的欢声笑语,追求远中的结伴同行 (笔者:JEEP/711)[JAVA笔记 | 时间:2017-05-12| JAVA 类加载与反射 ] 1.类加载 类加载器负责将 .class 文件(可能在磁盘上, 也可能在网络上) 加载到内存中, 并为之生成对应的 java.lang.Class 对象 当程序主动使用某个类时,如果该类还未被加载到内存中,系统会通过加载.连接.初始化三个步骤来对该类进行初始化,如果没

Java中的反射机制

Java反射的概念 Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制 Java反射机制主要提供下面几种用途: 1.在运行时判断任意一个对象所属的类 2.在运行时构造任意一个类的对象 3.在运行时判断任意一个类所具有的成员变量和方法 4.在运行时调用任意一个对象的方法 首先看一个简单的例子,通过这个例子来理解Java的反射机制是如何工作的 i

java中的反射

一.什么是反射 简单来说,java反射机制其实就是I/O流的一种封装版,用来快速读取硬盘上的class文件.class文件相当于一个身份证,JVM在操作某一个对象时,需要根据身份证获得对象拥有的属性和拥有的功能及方法.这种动态获取的信息以及动态调用对象方法的功能称为java语言的反射机制. 二.官方提供的反射机制API: class文件: java.lang.reflect.Class类:描述内存中class文件 属性(数据存储单位): java.lang.reflect.Field类:描述内存

Java语言中反射动态代理接口的解释与演示

Java语言中反射动态代理接口的解释与演示 Java在JDK1.3的时候引入了动态代理机制.可以运用在框架编程与平台编程时候捕获事件.审核数据.日志等功能实现,首先看一下设计模式的UML图解: 当你调用一个接口API时候,实际实现类继承该接口,调用时候经过proxy实现. 在Java中动态代理实现的两个关键接口类与class类分别如下: java.lang.reflect.Proxy java.lang.reflect.InvocationHandler 我们下面就通过InvocationHan

java进阶之反射:反射基础之如何获取一个类以及如何获取这个类的所有属性和方法(1)

java学习一段时间之后,大家可能经常会听到反射这个词,那么说明java已经学习到一个高一点的层次了.接下来我会一步步和大家一起揭开java高级特性反射的神秘面纱. 首先介绍下类对象这个概念,可能会经常用到这个概念: 类对象:java中有句很经典的话"万事万物皆对象",相信大家都不陌生,这句话告诉了我们java的特征之一,那就是面向对象.java中类的概念我们都很熟悉,既然万事万物皆是对象,那么类是谁的对象呢?<对象的概念:一个类的实例>换句话说,类是谁的实例.如此就有了类

java中利用反射机制绕开编译器对泛型的类型限制

首先看下面这个例子 public static void main(String[] args) { ArrayList<Integer> al1 = new ArrayList<Integer>(); al1.add(1); ArrayList<String> al2 = new ArrayList<String>(); al2.add("hello"); //int型链表和string型链表,结果为true System.out.pr

Java语言的反射机制 笔记 摘自 http://blog.csdn.net/kaoa000/article/details/8453371

在Java运行时环境中,对于任意一个类,能否知道这个类有哪些属性和方法?对于任意一个对象,能否调用它的任意一个方法?答案是肯定的.这种动态获取类的信息以及动态调用对象的方法的功能来自于Java 语言的反射(Reflection)机制. 1.Java 反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类.在运行时构造任意一个类的对象.在运行时判断任意一个类所具有的成员变量和方法.在运行时调用任意一个对象的方法 2.Reflection 是Java被视为动态(或准动态)语言的一个关键性质.

Java中的反射——(1)什么是反射

Java程序中的各个Java类属于同一类事物,描述这类事物的Java类名就是Class. public class ReflectTest { public static void main(String[] args) throws ClassNotFoundException { String str1 = "abc"; Class cls1 = String.class; Class cls2 = str1.getClass(); Class cls3 = Class.forNa

重踏学习Java路上_Day27(反射,模式设计,jdk新特性)

1:反射(理解) (1)类的加载及类加载器 (2)反射: 通过字节码文件对象,去使用成员变量,构造方法,成员方法 (3)反射的使用 A:通过反射获取构造方法并使用 B:通过反射获取成员变量并使用 C:通过反射获取成员方法并使用 (4)反射案例 A:通过反射运行配置文件的内容 B:通过反射越过泛型检查 C:通过反射给任意的一个对象的任意的属性赋值为指定的值 (5)动态代理 2:设计模式 (1)装饰设计模式 BufferedReader br = new BufferedReader(new Inp