Created
October 10, 2016 13:33
-
-
Save Viacheslav77/c0f47b53d4bad41236272d5c1dcb2942 to your computer and use it in GitHub Desktop.
Написать код, который сериализирует и десериализирует в/из файла все значения полей класса, которые отмечены аннотацией @save без использования стандартных средств серилизации.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Поля созданного объекта 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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package SaveFieldsSerializableAnnotation; | |
import java.lang.reflect.Field; | |
import java.util.Map; | |
public class FindFieldAnnotation { | |
public static void FindAnnotation (TestContainer 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); | |
} | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package SaveFieldsSerializableAnnotation; | |
public class Container { | |
private int con; | |
public Container(int con1){ | |
con=con1; | |
} | |
public Container(){ | |
con=1000; | |
} | |
public int getCon (){ | |
return con; | |
} | |
@Override | |
public String toString() { | |
return ""+con; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package SaveFieldsSerializableAnnotation; | |
import java.lang.reflect.Constructor; | |
import java.lang.reflect.Field; | |
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package SaveFieldsSerializableAnnotation; | |
import java.io.BufferedReader; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.io.PrintWriter; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class SaveOpenFields implements ISerialezare { | |
private static Map<String, Object> fieldsList = new HashMap<String, Object>(); | |
public static void SerializableFields (TestContainer obj, String patch){ | |
FindFieldAnnotation.FindAnnotation(obj, fieldsList); | |
try (PrintWriter writer = new PrintWriter(patch)) { | |
for (Map.Entry entry: fieldsList.entrySet()) | |
writer.println((String) entry.getKey() + ":" + entry.getValue() + ":" + entry.getValue().getClass()); | |
} catch (FileNotFoundException ex) { | |
ex.printStackTrace(); | |
} | |
} | |
@Override | |
public Object deSerializableFields(Class<?> cls, String patch){ | |
fieldsList.clear(); | |
try (BufferedReader reader = new BufferedReader(new FileReader(patch))) { | |
String line = ""; | |
while ((line = reader.readLine()) != null) { | |
String[] temp = line.split(":"); | |
fieldsList.put(temp[0], getObject (temp[1], temp[2])); | |
} | |
} | |
catch(IOException e){ | |
System.out.println("ERROR load group !!!"); | |
} catch (Exception e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
return LoadObj.DeSer(cls, fieldsList); | |
} | |
private Object getObject (String field, String className) throws Exception { | |
switch (className) { | |
case "class java.lang.Integer": | |
return Integer.valueOf(field); | |
case "class java.lang.String": | |
return field; | |
case "class SaveFieldsSerializableAnnotation.Container": | |
return new Container(Integer.valueOf(field)); | |
default: | |
throw new Exception(); | |
} | |
} | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package SaveFieldsSerializableAnnotation; | |
public class TestContainer { | |
@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