Java 서열화, 반사, 메모(1)
13884 단어 Java 기반
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 + "]";
}
}
미완성 미속...
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
검지offer프로그래밍 시험문제 자바 실현--4.두 갈래 나무를 재건하다소경 오빠 제목 설명: 두 갈래 나무의 앞 순서와 중간 순서의 결과를 입력하고 이 두 갈래 나무를 다시 만드십시오.입력한 앞 순서와 중간 순서의 결과에 중복된 숫자가 없다고 가정하십시오.예를 들어 앞 순서 반복 시퀀...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.