Advertisement

【JAVA】从0开始写DHT/磁力爬虫 02 Bencode实现

阅读量:

实现Bencode借用github上开源项目 做了一些改造

https://github.com/dampcake/bencode

新增方法encode(object o)

实际上是利用反射将复杂对象转为map

复制代码
     public static Map<String, Object> beanToMapComplate(Object bean) {

    
     if (bean == null) {
    
         return null;
    
     }
    
     Map<String, Object> map = new TreeMap<String, Object>();
    
     try {
    
         BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
    
         PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    
         for (PropertyDescriptor property : propertyDescriptors) {
    
             String key = property.getName();
    
             if (!key.equals("class")) {
    
                 Method getter = property.getReadMethod();// Java中提供了用来访问某个属性的 getter/setter方法
    
                 Object value = getter.invoke(bean);
    
                 if (value != null) {
    
                     Class<? extends Object> clazz = value.getClass();
    
                     if (!clazz.getName().startsWith("java") && !clazz.getName().startsWith("[")) {
    
                         Map<String, Object> beanToMapComplate = beanToMapComplate(value);
    
                         value = beanToMapComplate;
    
                     }
    
                     map.put(key, value);
    
                 }
    
             }
    
         }
    
     } catch (IntrospectionException e) {
    
         e.printStackTrace();
    
     } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    
         e.printStackTrace();
    
  
    
     }
    
     return map;
    
     }
    
    
    
    
    AI写代码

方便我们之后构建消息使用

全部评论 (0)

还没有任何评论哟~