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

本文介绍了一个用于构建枚举Json文件的自动化工具,该工具能够通过指定的包名获取所有类,并构建出相应的枚举Json。通过类加载器解析文件或jar包内的类,然后将这些类转换为Json格式进行保存。
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

package cn.njucm.dosepre.repository; import cn.njucm.dosepre.entity.Patient; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Optional; @Repository public interface PatientRepository extends JpaRepository<Patient, Long> { Optional findByPatientId(String patientId); List findByPatientNameContaining(String patientName); boolean existsByPatientId(String patientId); @Query(“SELECT p FROM Patient p WHERE p.age BETWEEN :minAge AND :maxAge”) List findByAgeRange(@Param(“minAge”) Integer minAge, @Param(“maxAge”) Integer maxAge); } package cn.njucm.dosepre.entity; import lombok.Data; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; @Data @Entity @Table(name = “patient”) public class Patient { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "patient_id", nullable = false, unique = true, length = 50) private String patientId; @Column(name = "patient_name", nullable = false, length = 100) private String patientName; @Enumerated(EnumType.STRING) private Gender gender; private Integer age; @Column(precision = 5, scale = 2) private BigDecimal weight; @Column(precision = 5, scale = 2) private BigDecimal height; @Column(precision = 5, scale = 2) private BigDecimal creatinine; @Column(name = "liver_function", length = 20) private String liverFunction; @Column(name = "kidney_function", length = 20) private String kidneyFunction; @Column(name = "create_time") @Temporal(TemporalType.TIMESTAMP) private Date createTime; @Column(name = "update_time") @Temporal(TemporalType.TIMESTAMP) private Date updateTime; public enum Gender { MALE, FEMALE } @PrePersist protected void onCreate() { createTime = new Date(); updateTime = new Date(); } @PreUpdate protected void onUpdate() { updateTime = new Date(); } }
最新发布
11-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值