Skip to content

Instantly share code, notes, and snippets.

@Viacheslav77
Created October 7, 2016 13:01
Show Gist options
  • Save Viacheslav77/f4424ab144b6a0ba05956c5ffffe7aa6 to your computer and use it in GitHub Desktop.
Save Viacheslav77/f4424ab144b6a0ba05956c5ffffe7aa6 to your computer and use it in GitHub Desktop.
Написать код, который сериализирует и десериализирует в/из файла все значения полей класса, которые отмечены аннотацией @save.
Поля созданного объекта testObj:
field1 = Hello @Save
field2 = 2 @Save
field3 = 10
field4 = 1 @Save
field5 = World
field6 = 5 @Save
Поля востановленного объекта testObjDeSer:
field1 = Hello @Save
field2 = 2 @Save
field3 = 1000
field4 = 1 @Save
field5 = null
field6 = 5 @Save
package SaveFieldsSerializableAnnotation;
import java.io.Serializable;
public class Container implements Serializable {
private int con;
public Container(int con1){
con=con1;
}
public Container(){
con=1000;
}
public int getCon (){
return con;
}
}
package SaveFieldsSerializableAnnotation;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Map;
public class FindFieldAnnotation {
public static void FindAnnotation (Serializable obj, Map<String, Object> fieldsList ){
Class<?> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for(Field field : fields){
if(field.isAnnotationPresent(Save.class)){
if(!field.isAccessible()){
field.setAccessible(true);
}
try {
fieldsList.put(field.getName(), field.get(obj));
}
catch (IllegalAccessException e){
System.out.println(e);
}
}
}
}
}
package SaveFieldsSerializableAnnotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class LoadObj {
public static Object DeSer (Class<?> cls, Map<String, Object> fieldsList){
Object obj = null;
try {
Constructor<?> ctr = cls.getConstructor();
obj = ctr.newInstance();
} catch (Exception ex) {
ex.printStackTrace();
}
Field[] fields = cls.getDeclaredFields();
for(Field field : fields){
if(field.isAnnotationPresent(Save.class) && fieldsList.containsKey(field.getName())){
if(!field.isAccessible()){
field.setAccessible(true);
}
try{
field.set(obj,fieldsList.get(field.getName()));
}
catch (IllegalAccessException e){
System.out.println(e);
}
}
}
return obj;
}
}
package SaveFieldsSerializableAnnotation;
/* Написать код, который сериализирует и десериализирует в/из файла
* все значения полей класса, которые отмечены аннотацией @Save.*/
public class Main {
public static void main (String ... arg){
//создаём новый обьект
TestContainer testObj = new TestContainer("Hello", 2, new Container(10), 1, "World", new Container(5));
System.out.println("Поля созданного объекта testObj:");
testObj.PrintField();
//серилизуем новый обьект
SaveOpenFields.SerializableFields(testObj, "d:\\1\\fields.txt");
//десериализуем обьект из файла и востанавливаем сохранённые поля
TestContainer testObjDeSer = (TestContainer) new SaveOpenFields().deSerializableFields(TestContainer.class, "d:\\1\\fields.txt");
System.out.println("Поля востановленного объекта testObjDeSer:");
testObjDeSer.PrintField();
}
}
package SaveFieldsSerializableAnnotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value=ElementType.FIELD)
@Retention(value= RetentionPolicy.RUNTIME)
public @interface Save {
}
package SaveFieldsSerializableAnnotation;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class SaveOpenFields {
private static Map<String, Object> fieldsList = new HashMap<String, Object>();
public static void SerializableFields (Serializable obj, String patch){
FindFieldAnnotation.FindAnnotation(obj, fieldsList);
try(ObjectOutputStream OOS = new ObjectOutputStream(new FileOutputStream(patch))){
OOS.writeObject(fieldsList);
}
catch (IOException e){
System.out.println(e);
}
}
public Object deSerializableFields(Class<?> cls, String patch){
try(ObjectInputStream OIS = new ObjectInputStream(new FileInputStream(patch))){
fieldsList = (HashMap<String, Object>) OIS.readObject();
}
catch(IOException |
ClassNotFoundException e){
System.out.println("ERROR load group !!!");
}
return LoadObj.DeSer(cls, fieldsList);
}
}
package SaveFieldsSerializableAnnotation;
import java.io.Serializable;
public class TestContainer implements Serializable {
@Save
public String field1;
@Save
private int field2;
private Container field3;
@Save
public int field4;
String field5;
@Save
private Container field6;
public TestContainer( String f1, int f2,Container f3,int f4, String f5, Container f6){
field1=f1;
field2=f2;
field3=f3;
field4=f4;
field5=f5;
field6=f6;
}
public TestContainer(){
field3 = new Container();
field6 = new Container();
}
public void PrintField (){
System.out.println( "field1 = " + field1 +" @Save"+ "\n"+
"field2 = " + field2 +" @Save"+ "\n"+
"field3 = " + field3.getCon() +"\n"+
"field4 = " + field4 +" @Save"+"\n"+
"field5 = " + field5 +"\n"+
"field6 = " + field6.getCon()+" @Save"+"\n" );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment