View Javadoc
1   package us.codecraft.webmagic.model.formatter;
2   
3   import us.codecraft.webmagic.model.annotation.Formatter;
4   
5   import java.lang.reflect.Field;
6   import java.util.List;
7   
8   /**
9    * @author code4crafter@gmail.com
10   * @since 0.7.0
11   *         Date: 2017/6/3
12   */
13  public class ObjectFormatterBuilder {
14  
15      private Field field;
16  
17      public ObjectFormatterBuilder setField(Field field) {
18          this.field = field;
19          return this;
20      }
21  
22      private ObjectFormatter initFormatterForType(Class<?> fieldClazz, String[] params) {
23          if (fieldClazz.equals(String.class) || List.class.isAssignableFrom(fieldClazz)){
24              return null;
25          }
26          Class<? extends ObjectFormatter> formatterClass = ObjectFormatters.get(BasicTypeFormatter.detectBasicClass(fieldClazz));
27          if (formatterClass == null) {
28              throw new IllegalStateException("Can't find formatter for field " + field.getName() + " of type " + fieldClazz);
29          }
30          return initFormatter(formatterClass, params);
31      }
32  
33      private ObjectFormatter initFormatter(Class<? extends ObjectFormatter> formatterClazz, String[] params) {
34          try {
35              ObjectFormatter objectFormatter = formatterClazz.newInstance();
36              objectFormatter.initParam(params);
37              return objectFormatter;
38          } catch (InstantiationException e) {
39              throw new RuntimeException(e);
40          } catch (IllegalAccessException e) {
41              throw new RuntimeException(e);
42          }
43      }
44  
45      public ObjectFormatter build() {
46          Formatter formatter = field.getAnnotation(Formatter.class);
47          if (formatter != null && !formatter.formatter().equals(Formatter.DEFAULT_FORMATTER)) {
48              return initFormatter(formatter.formatter(), formatter.value());
49          }
50          if (formatter == null || formatter.subClazz().equals(Void.class)) {
51              return initFormatterForType(field.getType(), formatter != null ? formatter.value() : null);
52          } else {
53              return initFormatterForType(formatter.subClazz(), formatter.value());
54          }
55      }
56  }