反射的小栗子 Object2QueryString

段干长恨
2023-12-01

写在文章前

在long long ago ,还在喜欢写爬虫的时候,写过一个object转QueryString的小工具,最近复习反射部分,想起来贴出来哈

Object2QueryString

注解:LHttpQueryString

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface HttpQueryString {
    String name() default "";
    boolean require() default true;
    String description() default "";
}

实现类:HttpQueryStringUtil


import java.lang.reflect.Field;

public class HttpQueryStringUtil {

    public static String objectToQueryString(Object obj)  {
        StringBuilder stringBuilder = new StringBuilder("?");
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object o = null;
            try {
                o = field.get(obj);
            } catch (IllegalAccessException e) {
                System.out.println("出现异常");
                e.printStackTrace();
            }
            if (field.getAnnotation(HttpQueryString.class) != null) {
                if (StringUtil.isNotEmpty(field.getAnnotation(HttpQueryString.class).name()) && field.getAnnotation(HttpQueryString.class).require()) {
                    stringBuilder.append(field.getAnnotation(HttpQueryString.class).name()).append("=").append(getBeanValue(o)).append("&");
                }
            } else if (o != null) {
                stringBuilder.append(field.getName()).append("=").append(getBeanValue(o)).append("&");
            }

        }
        String result = stringBuilder.toString();
        return result.length() > 0 ? result.substring(0, result.length() - 1) : "";
    }


    private static String getBeanValue(Object obj) {
        if (obj != null) {
            return obj.toString();
        }
        return "";
    }
    

}

 类似资料: