Advertisement
Leymooo

Untitled

Aug 27th, 2018
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. /**
  2. * Convert a class to array with strings
  3. *
  4. * @param lines a list where save all lines
  5. * @param root a class with config fields
  6. * @param instance a instance of this class
  7. */
  8. private void save(List<String> lines, Class root, final Object instance) {
  9. try {
  10. for (Field field : root.getDeclaredFields()) {
  11. if (field.getAnnotation(Ignore.class) != null) { //Skip this field
  12. continue;
  13. }
  14. Comment comment = field.getAnnotation(Comment.class);
  15. if (comment != null) { //Add comments
  16. for (String line : comment.value()) {
  17. lines.add("# " + line);
  18. }
  19. }
  20. Alias alias = field.getAnnotation(Alias.class);
  21. String name = alias == null ? field.getName() : alias.value();
  22. setAccessible(field);
  23. if (field.getAnnotation(Create.class) != null) {
  24. lines.add(toTableName(name));
  25. Class<?> current = field.getType();
  26. Object value = field.get(instance);
  27. if (value == null) {
  28. Constructor<?> constructor = current.getDeclaredConstructor();
  29. constructor.setAccessible(true);
  30. field.set(instance, value = constructor.newInstance());
  31. }
  32. save(lines, current, value); // read a fields from a section(table)
  33. } else {
  34. if (field.getAnnotation(AsMap.class) != null) {
  35. Map<String, ?> map = (Map<String, ?>) field.get(instance);
  36. for (Entry<String, ?> entry : map.entrySet()) {
  37. lines.add(entry + " = " + toString(entry.getValue()));
  38. }
  39. continue;
  40. }
  41. Object value = field.get(instance);
  42. if (field.getAnnotation(AsBytes.class) != null) {
  43. value = new String((byte[]) value, StandardCharsets.UTF_8);
  44. }
  45. lines.add(name + " = " + toString(value));
  46. lines.add("");
  47. }
  48. }
  49. } catch (IllegalAccessException | IllegalArgumentException | SecurityException | NoSuchFieldException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
  50. logger.log(Level.ERROR, "", e);
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement