指定包名下所有Enum生成json.js文件

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.core.io.VfsResource;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;


public final class BuildEnumJsonFileUtils {

    static final Logger LOGGER = Logger.getLogger(BuildEnumJsonFileUtils.class);

    public BuildEnumJsonFileUtils(String packageName) throws IOException, ClassNotFoundException {
        this.packageName = packageName;
        this.path = packageName.replace('.', '/');
        this.classList = getClassesByPackageName();


    }

    private String packageName;

    private List<String> classList;

    private String path;

    /**
     * 通过(包名/命名空间)获得所有类
     *
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public List<String> getClassesByPackageName() throws IOException, ClassNotFoundException {
        List<String> classList = new ArrayList<String>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL url = classLoader.getResource(path);
        String protocol = url.getProtocol();
        LOGGER.error("URL-FILE : " + url.getFile() + "*********************************************************");
        LOGGER.error("path : " + this.path + "*********************************************************");
        LOGGER.error("protocol : " + protocol + "*********************************************************");
        if (protocol.equals("file")) {
            File fileDirectory = new File(url.getFile());
            classList = findClasses(fileDirectory);
        } else if (protocol.equals("jar") || protocol.equals("vfszip")) {  //vfszip 兼容jboss
            JarFile jarFile = ((JarURLConnection) url.openConnection())
                    .getJarFile();
            classList = findClasses(jarFile);
        } else if (protocol.equals("vfszip")) {
            VfsResource v = new VfsResource(url.getContent());
            File fileDirectory = v.getFile();
            classList = findClasses(fileDirectory);
        }
        return classList;

    }

    /**
     * 通过文件夹所有类文件名
     *
     * @param directory 文件夹名称
     * @return
     * @throws ClassNotFoundException
     */
    public List<String> findClasses(File directory) throws ClassNotFoundException {
        List<String> classes = new ArrayList<String>();
        if (!directory.exists())
            return classes;
        File[] files = directory.listFiles();
        for (File file : files) {
            if (!file.getName().endsWith(".class")) continue;
            String clazzName = file.getName().replaceAll(".class", "");
            classes.add(packageName + "." + clazzName);
        }
        return classes;
    }

    public List<String> findClasses(JarFile jarFile) throws ClassNotFoundException {
        List<String> classes = new ArrayList<String>();
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (!(entry.getName().startsWith(path) && entry.getName().endsWith(".class"))) continue;
            // 将其变成全定限完整类名
            String clazzName = entry.getName().replaceAll(".class", "").replace("/", ".");
            classes.add(clazzName);
        }
        return classes;
    }


    /**
     * 构建枚举Json
     *
     * @param jsonFile 需要写入的json文件
     * @throws IOException
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    public void buildEnumJson(File jsonFile) {
        JsonGenerator jsonGenerator = null;
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(jsonFile), "UTF-8");
            addJsonEnumsHead(writer);
            jsonGenerator = new ObjectMapper().getJsonFactory().createJsonGenerator(writer);
            jsonGenerator.writeStartObject();
            this.buildJsonList(jsonGenerator);
            jsonGenerator.writeEndObject();
            // 先输出json
            jsonGenerator.flush();
            addJsonEnumsBottom(writer);
            jsonGenerator.close();
            writer.close();
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } finally {
            jsonGenerator = null;
            writer = null;
        }
    }

    /**
     * 构建Json列表
     *
     * @param jsonGenerator json生成器
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws IOException
     * @throws JsonGenerationException
     * @throws JsonProcessingException
     */
    private void buildJsonList(JsonGenerator jsonGenerator)
            throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException,
            IOException, JsonGenerationException, JsonProcessingException {
        if (classList.size() == 0) return;
        String className = classList.get(0);
        Class<?> enumz = Class.forName(className);
        jsonGenerator.writeFieldName(enumz.getSimpleName());
        Map<String, Map<String, String>> enumMap = getEnumElementMap(enumz);
        jsonGenerator.writeObject(enumMap);
        classList.remove(0);
        buildJsonList(jsonGenerator);
    }

    /**
     * 获得枚举类元素Map
     *
     * @param enumz 枚举类Class
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    private Map<String, Map<String, String>> getEnumElementMap(Class<?> enumz) throws NoSuchMethodException,
            IllegalAccessException, InvocationTargetException {
        Map<String, Map<String, String>> enumMap = new LinkedHashMap<String, Map<String, String>>();
        Method values = enumz.getMethod("values");
        Method getTitleMethod = enumz.getMethod("getTitle");
        Method getValueMethod = enumz.getMethod("getValue");
        Object returnElement = values.invoke(enumz);
        for (Object element : (Object[]) returnElement) {
            Map<String, String> tempMap = new LinkedHashMap<String, String>();
            String title = (String) getTitleMethod.invoke(element);
            tempMap.put("title", title);
            String value = (String) getValueMethod.invoke(element);
            tempMap.put("value", value);
            enumMap.put(element.toString(), tempMap);
        }
        return enumMap;
    }


    private void addJsonEnumsHead(Writer writer) throws IOException {
        writer.write("var enumJson = ");
    }

    private void addJsonEnumsBottom(Writer writer) throws IOException {
        writer.append(";");
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        BuildEnumJsonFileUtils buildJson = new BuildEnumJsonFileUtils("com.zskx.ipem.enums");
        String jsonPath = "usefullJson.js";
        File jsonFile = new File(jsonPath);
        buildJson.buildEnumJson(jsonFile);
    }

}

转载于:https://my.oschina.net/tianvo/blog/160355

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值