Java 서열화, 반사, 메모(1)

13884 단어 Java 기반
서열화: 서열화가 무엇인지, 왜 서열화를 하는지, 한 장면을 고려하고 이런 응용은 한 대상을 영구적으로 저장할 때 발생하는지 고려하여 컴퓨터 디스크에 저장할 수도 있고 데이터베이스에 저장할 수도 있다.이 대상을 필요로 할 때 디스크나 데이터베이스에서 꺼낼 수 있다.예를 들어 class People {String name, int age} 라는 클래스 정의가 있는데, 나는 지금 People one = new People (), one.name = "장삼"age= 24. 현재 원이라는 대상이 생겼는데 그 안에 장삼의 정보가 포함되어 있다. 나는 지금 원을 데이터베이스에 영구적으로 저장할 수 있다. 내가 어느 날 장삼을 생각하면 원을 데이터베이스에서 읽을 수 있다.우리는 원이라는 대상을 얻었으니 또 진일보한 조작을 할 수 있다.(주의: 서열화는 클래스의 상태, 즉 클래스의 구성원 변수만 저장하면 된다. 임시 변수와 방법은 서열화에 아무런 의미가 없다)
Demo1 Person.java:
package com.mq.class1;

import java.io.Serializable;

public class Person implements Serializable {

	private static final long serialVersionUID = 5209339615516670L;
	private String name;
	private int age;

	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + "]";
	}

}


Person 객체를 파일로 시리얼화하려면 다음과 같이 하십시오.
package com.mq.class1;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 *  Person           
 * 
 * @author Administrator
 * 
 */
public class WritePerson {

	public static void main(String[] args) {
		String path = "src/person.bin";
		FileOutputStream fileOutputStream = null;
		ObjectOutputStream oStream = null;

		try {
			fileOutputStream = new FileOutputStream(path);
			oStream = new ObjectOutputStream(fileOutputStream);
			Person person = new Person("zhangsan", 18);
			oStream.writeObject(person);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (oStream != null) {
				try {
					oStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}


시리얼화된 파일을 읽으려면 다음과 같이 하십시오.
package com.mq.class1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 *          
 * 
 * @author Administrator
 * 
 */
public class ReadPerson {

	public static void main(String[] args) {
		String path = "src/person.bin";
		FileInputStream fileInputStream = null;
		ObjectInputStream inputStream = null;
		try {
			fileInputStream = new FileInputStream(path);
			inputStream = new ObjectInputStream(fileInputStream);
			Person person = (Person) inputStream.readObject();
			if (person != null) {
				System.out.println(person);
			} else {
				System.out.println("     ");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
				if (fileInputStream != null) {
					fileInputStream.close();
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}
}


bean 대상을 xml 파일로 바꿀 수 있지만, 이 몇 개의jar 패키지가 필요합니다.http://download.csdn.net/detail/chaogu94/9618822 Demo2: Person.자바는 이전과 같다.시리얼화된 객체를 xml 파일로 변환하려면 다음과 같이 하십시오.
package com.mq.class1.seriazabletoxml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

/**
 *             xml  
 * @author Administrator
 *
 */
public class WritePersonToXML {

	public static void main(String[] args) {
		String path = "src/person.xml";
		FileOutputStream fileOutputStream = null;
		List persons = new ArrayList();
		try {
			fileOutputStream = new FileOutputStream(path);
			for (int i = 0; i < 3; i++) {
				Person person = new Person("zhangsan" + i + 1, i + 1);
				persons.add(person);
			}
			//    XStream  ,     toXML                 xml  
			XStream xStream = new XStream();
			xStream.toXML(persons, fileOutputStream);

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
}


시리얼화된 다음에 생성된 xml 파일을 읽으려면 다음과 같이 하십시오.
package com.mq.class1.seriazabletoxml;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

/**
 *            xml  
 * 
 * @author Administrator
 * 
 */
public class ReadPersonFromXML {

	public static void main(String[] args) {
		String path = "src/person.xml";
		List persons = null;
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream(path);
			XStream xStream = new XStream();
			persons = (ArrayList) xStream.fromXML(inputStream);
			System.out.println(persons);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (inputStream != null)
				try {
					inputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

	}
}


반사: 개념: JAVA 반사 메커니즘은 운행 상태에서 임의의 클래스에 대해 이 클래스의 모든 속성과 방법을 알 수 있다.임의의 대상에 대해 임의의 방법과 속성을 호출할 수 있다.이런 동적으로 얻은 정보와 동적 호출 대상의 방법의 기능을 자바 언어의 반사 메커니즘이라고 한다.
Person 클래스:
package com.mq.class1.reflect;

/**
 *          、    、    、     ,           ,         
 * @author Administrator
 *
 */
public class Person {
	public static String TAG = "Person";
	public static String getTAG(){
		return TAG;
	}
	public int id = 10;
	private String name;
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	private void setAge(int age) {
		this.age = age;
	}

	public Person() {
		super();
		// this.id=10;
		// TODO Auto-generated constructor stub
	}

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

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	public int sum(int... numbers) {
		int total = 0;
		for (int n : numbers)
			total += n;
		return total;
	}

}


Class를 만들려면 다음과 같이 하십시오.
package com.mq.class1.reflect;

public class ReflectTest {

	public static void main(String[] args) throws ClassNotFoundException,
			InstantiationException, IllegalAccessException {
		/*
		 *   Class     
		 */
		// 1.      
		Class> class1 = Person.class;
		// 2.       
		Person person = new Person();
		Class> class2 = person.getClass();
		// 3.  forName     
		Class> class3 = Class.forName("com.mq.class1.reflect.Person");
		//            class    ,    true
		System.out.println(class1 == class2);
		System.out.println(class2 == class3);

		/*
		 *     
		 */
		Person person2 = (Person) class1.newInstance();
		System.out.println(person2);
	}
}


Field 작업:
package com.mq.class1.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class FieldTest {

	public static void main(String[] args) throws SecurityException,
			NoSuchFieldException, IllegalArgumentException,
			IllegalAccessException {
		/*
		 *         Field  
		 */
		Class> class1 = Person.class;
		Person person = new Person(101, "zhangsan", 18);
		Field field = class1.getField("id");
		//       id   
		System.out.println(field);
		Object object = field.get(person);
		System.out.println(object);

		/*
		 *         Field  
		 */
		field = class1.getDeclaredField("age");
		System.out.println(field);
		//                 true
		field.setAccessible(true);
		object = field.get(person);
		System.out.println(object);
		//   person age  
		field.set(person, 100);
		System.out.println(person.getAge());

		/*
		 *        
		 */
		Field[] fields = class1.getDeclaredFields();
		for (Field field2 : fields) {
			System.out.println(field2);
		}

		/*
		 *       
		 */
		field = class1.getDeclaredField("TAG");
		System.out.println("          :"
				+ Modifier.isStatic(field.getModifiers()));
		//      
		field.setAccessible(true);
		object = field.get(null);//          ,   null
		System.out.println(object);
		field.set(null, "new value");
		System.out.println(Person.getTAG());
	}
}


Construct: 직원 클래스 Employee를 새로 만듭니다.java
package com.mq.class1.reflect;

public class Employee {

	private static Employee employee;//            
	private int id;
	private String name;

	private Employee() {

	}

	private Employee(int id, String name) {
		this.id = id;
		this.name = name;
	}

	public static Employee getInstance() {
		if (employee == null)
			employee = new Employee();
		return employee;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}

}


ConstructTest:
package com.mq.class1.reflect;

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

public class ConstructTest {

	public static void main(String[] args) throws InstantiationException,
			IllegalAccessException, SecurityException, NoSuchMethodException,
			IllegalArgumentException, InvocationTargetException {
		//     /           
		Class> class1 = Person.class;
		Person person = (Person) class1.newInstance();
		System.out.println(person);

		//              (  )
		Constructor constructor = (Constructor) class1
				.getConstructor(int.class, String.class, int.class);
		person = constructor.newInstance(12, "zhangsan", 20);
		System.out.println(person);

		//  Employee            
		Class empClass = Employee.class;
		Constructor empConstructor = empClass
				.getDeclaredConstructor();
		empConstructor.setAccessible(true);
		Employee employee = empConstructor.newInstance();
		System.out.println(employee);

		//  Employee            
		empClass = Employee.class;
		empConstructor = empClass
				.getDeclaredConstructor(int.class,String.class);
		empConstructor.setAccessible(true);
		employee = empConstructor.newInstance(101,"zhang");
		System.out.println(employee);
	}
}


Method:
package com.mq.class1.reflect;

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

/**
 *       
 * 
 * @author Administrator
 * 
 */
public class MethodTest {

	public static void main(String[] args) throws SecurityException,
			NoSuchMethodException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException {
		/*
		 *   get  
		 *                
		 */
		Person person = new Person(101, "zhangsan", 20);
		Class class1 = Person.class;
		Method method = class1.getDeclaredMethod("getAge");//        ,      ,           
		int age = (Integer) method.invoke(person);
		System.out.println(age);//    20

		/*
		 *   set  
		 *               
		 */
		method = class1.getDeclaredMethod("setAge", int.class);
		method.setAccessible(true);
		method.invoke(person, 30);
		System.out.println(person.getAge());//    30

		/*
		 *         
		 *              
		 */
		method = class1.getDeclaredMethod("sum", int[].class);
		age = (Integer) method.invoke(person, new int[] { 1, 2, 3 });
		System.out.println(age);//    6
	}

}


반사 사례에 따라 요구: 하나의 클래스의 모든 필드와 값을 반사할 수 있는 방법을 제공합니다
package com.mq.class1.reflect;

import java.lang.reflect.Field;

public class MethodDemo {

	public static void main(String[] args) throws IllegalArgumentException,
			IllegalAccessException {

		Person person = new Person(101, "zhangsan", 20);
		String string = toString(person);
		System.out.println(string);
	}

	public static String toString(Object obj) throws IllegalArgumentException,
			IllegalAccessException {
		StringBuilder builder = new StringBuilder();
		Class> class1 = obj.getClass();
		Field[] fields = class1.getDeclaredFields();

		for (Field field : fields) {
			field.setAccessible(true);
			builder.append(field.getName());
			builder.append("=");
			builder.append(field.get(obj));
			builder.append(", ");
		}
		if (builder.length() > 0) {
			builder.delete(builder.length() - 2, builder.length());
		}
		return class1.getSimpleName() + "[" + builder + "]";
	}

}


미완성 미속...

좋은 웹페이지 즐겨찾기