java笔记

winmerge web site- You will see the difference… 文件对比软件

    long num = list.parallelStream().filter(x -> x.length() < 5).count();

Stream stream = users.stream() //创建通道流
.filter((x) -> { //过滤通道流
Boolean flag = x.getAge() > 20;
return flag;
});

public static void main(String[] args) {
    OrgEmployeeInfo orgEmployeeInfo = new OrgEmployeeInfo();
    orgEmployeeInfo.setId(1L);
    orgEmployeeInfo.setEmpname("张三");
    OrgEmployeeInfo orgEmployeeInfo1 = new OrgEmployeeInfo();
    orgEmployeeInfo1.setId(2L);
    orgEmployeeInfo1.setEmpname("李四");
    OrgEmployeeInfo orgEmployeeInfo3 = new OrgEmployeeInfo();
    orgEmployeeInfo3.setId(3L);
    orgEmployeeInfo3.setEmpname("张三");
    ArrayList<OrgEmployeeInfo> orgEmployeeInfos = new ArrayList<>();
    orgEmployeeInfos.add(orgEmployeeInfo);
    orgEmployeeInfos.add(orgEmployeeInfo1);
    orgEmployeeInfos.add(orgEmployeeInfo3);
    //根据id去重
    List<OrgEmployeeInfo> unique = orgEmployeeInfos.stream().collect(
            collectingAndThen(
                    toCollection(() -> new TreeSet<>(comparing(OrgEmployeeInfo::getId))), ArrayList::new)
    );
    //根据岗位和id去重----多个属性去重
    List<OrgEmployeeInfo> unique1 = orgEmployeeInfos.stream().collect(
            collectingAndThen(
                    toCollection(() -> new TreeSet<>(comparing(o -> o.getId() + ";" + o.getPostid()))), ArrayList::new)
    );
    //转map  ***转map时如果有相同的key会报错

// Map<Long, String> collect = unique.stream().collect(Collectors.toMap(OrgEmployeeInfo::getId, OrgEmployeeInfo::getEmpname));
Map<Long, String> collect = orgEmployeeInfos.stream().collect(Collectors.toMap(OrgEmployeeInfo::getId, OrgEmployeeInfo::getEmpname));
//map遍历
collect.forEach((k, v) -> System.out.println("key:value = " + k + “:” + v));
unique.forEach(o -> System.out.println(o.getId()));

//两个集合双循环根据对象的id进行匹配 如果匹配到了就赋值给外层循环的对象生成一个新集合 匹配赋值用 外边的应该放集合元素少的一方才对
if (resp.getPushPhase().equals(“1”)) {
// 设置物品信息
List allGoodsInfo = iGoodsService.getAllGoodsInfo(new PushChasingGoodsInfoBO());
List list = pushChasingGoodsInfoVOS.stream().map(
allGoodsIn -> allGoodsInfo.stream().filter(
goodsIn -> allGoodsIn.getId().equals(goodsIn.getId())).findFirst().map(goods -> {
allGoodsIn.setGoodsName(goods.getGoodsName());
allGoodsIn.setGoodsCode(goods.getGoodsCode());
allGoodsIn.setGoodsPic(goods.getGoodsPic());
allGoodsIn.setGoodState(goods.getGoodState());
allGoodsIn.setGoodsType(goods.getGoodsType());
return allGoodsIn;
}).orElse(null)).collect(Collectors.toList());
resp.setPushChasingGoodsInfoVOS(list);
}

		//筛选
 	final int lenthForLimit = lengthL;
    	    ArrayList<Integer> integers = new ArrayList<>();
     	   for (int i = 1; i <= lenthForLimit; i++ ) {
      	      integers.add(i);
      	  }
     	   List<OrgDepartmentInfoBO> collect = orgDepartmentInfoSon.stream().filter(
       	     org -> integers.contains(org.getLevel().split(",").length)).collect(Collectors.toList());
       	 orgDepartmentInfoBOS.addAll(collect);//筛选结束

/**
* sort按指定方式排序
*/
distinctList.sort((e1, e2) -> e1 < e2 ? 1 : -1);
System.out.println(distinctList); // 递减排列

//
// Source code recreated from a .class file by IntelliJ IDEA 赋值类属性值
// (powered by Fernflower decompiler)
//

package com.airtimes.mcrsv.publics.common.utils;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class AirBeanUtils {
private static AirBeanUtils.PooledMap<String, List<AirBeanUtils.FM>> cache = new AirBeanUtils().new PooledMap();
private static final String OBJECT_STR = “java.lang.Object”;
private static final byte NULL = 0;
private static final byte COLLECTION_TYPE = 1;
private static final byte MAP_TYPE = 2;
private static final byte ARRAY_TYPE = 3;
private static final byte OTHER_TYPE = 4;
private static final byte DATE_TYPE = 5;
private static final byte BIG_DECIMAL_TYPE = 6;

public AirBeanUtils() {
}

public static void copyObject(Object sour, Object targ, Class<?>... types) {
    if (sour != null && targ != null) {
        Class<?> sClass = sour.getClass();
        Class<?> tClass = targ.getClass();
        switch(type(sClass)) {
        case 1:
            assignCollection(sour, targ, types);
            break;
        case 2:
            assignMap(sour, targ, types);
            break;
        case 3:
            assignArray(getDimensionType(tClass), sour, targ, types);
            break;
        case 4:
        default:
            List<AirBeanUtils.FM> allMF = null;
            String key = tClass.getName() + "=" + sClass.getName();
            if (cache.containsKey(key)) {
                allMF = (List)cache.get(key);
            } else {
                allMF = allMF(sClass, tClass);
                cache.put(key, allMF);
            }

            if (allMF != null && !allMF.isEmpty()) {
                Iterator var7 = allMF.iterator();

                while(var7.hasNext()) {
                    AirBeanUtils.FM fm = (AirBeanUtils.FM)var7.next();

                    try {
                        assignField(sour, targ, fm);
                    } catch (Exception var10) {
                        var10.printStackTrace();
                    }
                }

                return;
            }

            return;
        case 5:
            if (type(tClass) == 5) {
                ((Date)targ).setTime(((Date)sour).getTime());
            }
        }

    }
}

private static List<AirBeanUtils.FM> allMF(Class<?> szlass, Class<?> tzlass) {
    List<Field> sfields = getAllField(szlass);
    List<Field> tfields = getAllField(tzlass);
    if (sfields != null && !sfields.isEmpty() && tfields != null && !tfields.isEmpty()) {
        Map<String, Field> tfieldMap = new HashMap(sfields.size());
        Iterator var5 = tfields.iterator();

        while(var5.hasNext()) {
            Field field = (Field)var5.next();
            String name = field.getName();
            if (!tfieldMap.containsKey(name)) {
                tfieldMap.put(name, field);
            }
        }

        List<AirBeanUtils.FM> list = new ArrayList();
        Map<String, AirBeanUtils.FM> fmMap = new HashMap();
        Iterator var17 = sfields.iterator();

        while(true) {
            Field sfield;
            String name;
            Field tfield;
            while(true) {
                if (!var17.hasNext()) {
                    if (!fmMap.isEmpty()) {
                        var17 = fmMap.values().iterator();

                        while(var17.hasNext()) {
                            AirBeanUtils.FM fm = (AirBeanUtils.FM)var17.next();
                            list.add(fm);
                        }
                    }

                    return list;
                }

                sfield = (Field)var17.next();
                name = sfield.getName();
                tfield = null;
                if (tfieldMap.containsKey(name)) {
                    tfield = (Field)tfieldMap.get(name);
                    break;
                }

                name = name.replace("VO", "BO");
                if (tfieldMap.containsKey(name)) {
                    tfield = (Field)tfieldMap.get(name);
                    break;
                }

                name = name.replace("BO", "VO");
                if (tfieldMap.containsKey(name)) {
                    tfield = (Field)tfieldMap.get(name);
                    break;
                }

                name = name.replace("vo", "bo");
                if (tfieldMap.containsKey(name)) {
                    tfield = (Field)tfieldMap.get(name);
                    break;
                }

                name = name.replace("bo", "vo");
                if (tfieldMap.containsKey(name)) {
                    tfield = (Field)tfieldMap.get(name);
                    break;
                }
            }

            if (!fmMap.containsKey(name)) {
                try {
                    Method getter = szlass.getMethod("get" + initialUp(sfield.getName()));
                    Method setter = tzlass.getMethod("set" + initialUp(tfield.getName()), tfield.getType());
                    AirBeanUtils.FM fm = new AirBeanUtils().new FM();
                    fm.setter = setter;
                    fm.getter = getter;
                    fm.sfield = sfield;
                    fm.tfield = tfield;
                    fmMap.put(name, fm);
                } catch (Exception var14) {
                }
            }
        }
    } else {
        return null;
    }
}

private static List<Field> getAllField(Class<?> zlass) {
    if (zlass == null) {
        return null;
    } else {
        Field[] declaredFields = zlass.getDeclaredFields();
        List<Field> fields = new ArrayList(declaredFields.length + 10);
        if (declaredFields != null && declaredFields.length >= 0 && declaredFields != null && declaredFields.length > 0) {
            Field[] var3 = declaredFields;
            int var4 = declaredFields.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                Field field = var3[var5];
                fields.add(field);
            }
        }

        Class<?> superclass = zlass.getSuperclass();
        if (superclass != null && !"java.lang.Object".equals(superclass.getName())) {
            List<Field> allField = getAllField(superclass);
            if (allField != null && !allField.isEmpty()) {
                fields.addAll(allField);
                return fields;
            } else {
                return allField;
            }
        } else {
            return fields;
        }
    }
}

private static void assignMap(Object sour, Object targ, Class<?>[] types) {
    try {
        Object tko;
        Object tvo;
        if (type(targ.getClass()) == 2) {
            for(Iterator var3 = ((Map)sour).entrySet().iterator(); var3.hasNext(); ((Map)targ).put(tko, tvo)) {
                java.util.Map.Entry<?, ?> entry = (java.util.Map.Entry)var3.next();
                tko = null;
                tvo = null;
                if (types != null && types.length > 0) {
                    tko = getValue(types[0], entry.getKey(), subArray(types, 1, types.length - 1));
                    if (types.length > 1) {
                        tvo = getValue(types[1], entry.getValue(), subArray(types, 2, types.length - 2));
                    } else {
                        tvo = getValue(entry.getValue().getClass(), entry.getValue());
                    }
                } else {
                    tko = getValue(entry.getKey().getClass(), entry.getKey());
                    tvo = getValue(entry.getValue().getClass(), entry.getValue());
                }
            }
        }
    } catch (Exception var7) {
        var7.printStackTrace();
    }

}

private static void assignCollection(Object sour, Object targ, Class<?>... types) {
    if (type(targ.getClass()) == 1) {
        Iterator iterator = ((Collection)sour).iterator();

        Object to;
        try {
            for(; iterator.hasNext(); ((Collection)targ).add(to)) {
                Object so = iterator.next();
                to = null;
                if (types != null && types.length > 0) {
                    to = getValue(types[0], so, subArray(types, 1, types.length - 1));
                } else {
                    to = getValue(so.getClass(), so);
                }
            }
        } catch (Exception var6) {
            var6.printStackTrace();
        }
    }

}

private static void assignField(Object sour, Object targ, AirBeanUtils.FM fm) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
    Method getter = fm.getter;
    Method setter = fm.setter;
    Field sfield = fm.sfield;
    Field tfield = fm.tfield;
    if (getter != null && setter != null && sfield != null && tfield != null) {
        Object so;
        Object to;
        if (!sfield.getType().equals(tfield.getType())) {
            if (typeEquals(sfield.getType(), tfield.getType())) {
                setter.invoke(targ, getter.invoke(sour));
            } else if (!isPrimitive(tfield.getType()) && !isPackclass(tfield.getType()) && !isPrimitive(sfield.getType()) && !isPackclass(sfield.getType())) {
                so = getter.invoke(sour);
                if (so == null) {
                    return;
                }

                to = tfield.getType().newInstance();
                copyObject(so, to);
                setter.invoke(targ, to);
            }
        } else if (!isPrimitive(sfield.getType()) && !isPackclass(sfield.getType())) {
            if (type(sfield.getType()) == 6) {
                if (type(tfield.getType()) != 6) {
                    return;
                }

                so = getter.invoke(sour);
                if (so == null) {
                    return;
                }

                setter.invoke(targ, new BigDecimal(((BigDecimal)so).toPlainString()));
            } else if (type(sfield.getType()) == 1) {
                if (type(tfield.getType()) != 1) {
                    return;
                }

                Type tGenericity = ((ParameterizedType)tfield.getGenericType()).getActualTypeArguments()[0];
                Collection<?> sColl = (Collection)getter.invoke(sour);
                if (sColl == null) {
                    return;
                }

                Collection<Object> tColl = (Collection)sColl.getClass().newInstance();
                Iterator<?> iterator = sColl.iterator();
                if (iterator != null) {
                    while(iterator.hasNext()) {
                        Object to = getValue(tGenericity, iterator.next());
                        tColl.add(to);
                    }
                }

                setter.invoke(targ, tColl);
            } else if (type(sfield.getType()) == 2) {
                if (type(tfield.getType()) != 2) {
                    return;
                }

                Map<?, ?> cMap = (Map)getter.invoke(sour);
                if (cMap == null) {
                    return;
                }

                Type keyType = ((ParameterizedType)tfield.getGenericType()).getActualTypeArguments()[0];
                Type valueType = ((ParameterizedType)tfield.getGenericType()).getActualTypeArguments()[1];
                Map<Object, Object> tMap = (Map)cMap.getClass().newInstance();
                Iterator var21 = cMap.entrySet().iterator();

                while(var21.hasNext()) {
                    java.util.Map.Entry<?, ?> en = (java.util.Map.Entry)var21.next();
                    Object tko = getValue(keyType, en.getKey());
                    Object tvo = getValue(valueType, en.getValue());
                    tMap.put(tko, tvo);
                }

                setter.invoke(targ, tMap);
            } else {
                so = getter.invoke(sour);
                if (so == null) {
                    return;
                }

                to = tfield.getType().newInstance();
                copyObject(so, to);
                setter.invoke(targ, to);
            }
        } else {
            so = getter.invoke(sour);
            if (so == null) {
                return;
            }

            setter.invoke(targ, so);
        }

    }
}

private static Class<?>[] subArray(Class<?>[] classes, int start, int length) {
    Class<?>[] claArr = null;
    if (classes.length >= start + length) {
        claArr = new Class[length];

        for(int i = 0; i < length; ++i) {
            claArr[i] = classes[start];
            ++start;
        }
    }

    return claArr;
}

private static Object getValue(Class<?> zlass, Object value, Class<?>... types) throws IllegalAccessException, InstantiationException {
    if (value == null) {
        return null;
    } else {
        Object o = null;
        if (zlass != null) {
            if (!isPackclass(zlass)) {
                o = zlass.newInstance();
                copyObject(value, o, types);
            } else {
                o = value;
            }
        } else if (!isPackclass(value.getClass())) {
            o = value.getClass().newInstance();
            copyObject(value, o, types);
        } else {
            o = value;
        }

        return o;
    }
}

private static Object getValue(Type type, Object value, Class<?>... types) throws IllegalAccessException, InstantiationException {
    if (value == null) {
        return null;
    } else if (type(type) == 4) {
        return getValue((Class)type, value, types);
    } else {
        Type[] actualTypeArguments = ((ParameterizedType)type).getActualTypeArguments();
        Object o = value.getClass().newInstance();
        List<Class<?>> typeList = new LinkedList();
        int i;
        int s;
        if (actualTypeArguments != null && actualTypeArguments.length > 0) {
            Type[] var6 = actualTypeArguments;
            i = actualTypeArguments.length;

            for(s = 0; s < i; ++s) {
                Type t = var6[s];
                if (t != null) {
                    if (t instanceof ParameterizedType) {
                        LinkedList<Class<?>> genericityTypes = getGenericityTypes(type, value);
                        genericityTypes.removeFirst();
                        typeList.addAll(genericityTypes);
                    } else {
                        typeList.add((Class)t);
                    }
                }
            }
        }

        Class<?>[] classArr = new Class[types.length + typeList.size()];
        i = 0;

        for(s = typeList.size(); i < s; ++i) {
            classArr[i] = (Class)typeList.get(i);
        }

        i = 0;

        for(s = types.length; i < s; ++i) {
            classArr[i + s] = types[i];
        }

        copyObject(value, o, classArr);
        return o;
    }
}

private static LinkedList<Class<?>> getGenericityTypes(Type type, Object obj) throws IllegalAccessException {
    Class<?> class1 = obj.getClass();
    LinkedList<Class<?>> list = new LinkedList();
    if (type instanceof ParameterizedType) {
        Type rawType = ((ParameterizedType)type).getRawType();
        Type[] actualTypeArguments = ((ParameterizedType)type).getActualTypeArguments();
        list.add(class1);
        if (type(rawType) != type(class1)) {
            throw new IllegalAccessException();
        }

        if (type(class1) == 1) {
            Iterator iterator = ((Collection)obj).iterator();

            while(iterator.hasNext()) {
                Object next = iterator.next();
                if (next != null) {
                    list.addAll(getGenericityTypes(actualTypeArguments[0], next));
                    break;
                }
            }
        } else if (type(class1) == 2) {
            Set<java.util.Map.Entry<?, ?>> entrySet = ((Map)obj).entrySet();
            Iterator var12 = entrySet.iterator();

            Object key;
            Object value;
            do {
                if (!var12.hasNext()) {
                    return list;
                }

                java.util.Map.Entry<?, ?> entry = (java.util.Map.Entry)var12.next();
                key = entry.getKey();
                value = entry.getValue();
            } while(key == null && value == null);

            list.addAll(getGenericityTypes(actualTypeArguments[0], key));
            list.addAll(getGenericityTypes(actualTypeArguments[1], value));
        }
    } else {
        list.add((Class)type);
    }

    return list;
}

private static boolean typeEquals(Class<?> c1, Class<?> c2) {
    boolean sign1 = isPrimitive(c1);
    boolean sign2 = isPackclass(c2);
    if (!sign1 ^ sign2) {
        Class packclass;
        if (sign1) {
            packclass = packClassType(c1);
            return c2.equals(packclass);
        } else {
            packclass = packClassType(c2);
            return c1.equals(packclass);
        }
    } else {
        return false;
    }
}

private static Class<?> packClassType(Class<?> zlass) {
    if (zlass.equals(Integer.TYPE)) {
        return Integer.class;
    } else if (zlass.equals(Double.TYPE)) {
        return Double.class;
    } else if (zlass.equals(Long.TYPE)) {
        return Long.class;
    } else if (zlass.equals(Short.TYPE)) {
        return Short.class;
    } else if (zlass.equals(Byte.TYPE)) {
        return Byte.class;
    } else if (zlass.equals(Character.TYPE)) {
        return Character.class;
    } else if (zlass.equals(Boolean.TYPE)) {
        return Boolean.class;
    } else {
        return zlass.equals(Float.TYPE) ? Float.class : null;
    }
}

private static boolean isPrimitive(Class<?> zlass) {
    return zlass.isPrimitive();
}

private static boolean isPackclass(Class<?> zlass) {
    Class<?>[] types = new Class[]{Integer.class, Double.class, Float.class, Long.class, Short.class, Byte.class, Boolean.class, Character.class, String.class};
    Class[] var2 = types;
    int var3 = types.length;

    for(int var4 = 0; var4 < var3; ++var4) {
        Class<?> type = var2[var4];
        if (zlass.equals(type)) {
            return true;
        }
    }

    return false;
}

private static String initialUp(String str) {
    if (str != null && !"".equals(str.trim())) {
        char[] chars = str.toCharArray();
        chars[0] = (char)(chars[0] - 32);
        return new String(chars);
    } else {
        return null;
    }
}

private static void assignArray(Class<?> dimensionType, Object sour, Object targ, Class<?>[] types) {
    Class<?> tClass = targ.getClass();
    Class<?> componentType = tClass.getComponentType();
    int length = Array.getLength(sour);

    for(int i = 0; i < length; ++i) {
        Object so = Array.get(sour, i);
        if (!isPrimitive(componentType) && !isPackclass(componentType)) {
            Object to = null;
            if (componentType.isArray()) {
                int[] lengthArr = getLengthList(componentType, so);
                to = Array.newInstance(dimensionType, lengthArr);
            } else {
                try {
                    to = dimensionType.newInstance();
                } catch (Exception var11) {
                    var11.printStackTrace();
                }
            }

            copyObject(so, to, types);
            Array.set(targ, i, to);
        } else {
            Array.set(targ, i, so);
        }
    }

}

private static int[] getLengthList(Class<?> zlass, Object sour) {
    ArrayList lengthList;
    for(lengthList = new ArrayList(); zlass.isArray(); sour = Array.get(sour, 0)) {
        lengthList.add(Array.getLength(sour));
        zlass = zlass.getComponentType();
    }

    int[] arr = null;
    if (!lengthList.isEmpty()) {
        arr = new int[lengthList.size()];

        for(int i = 0; i < arr.length; ++i) {
            arr[i] = (Integer)lengthList.get(i);
        }
    }

    return arr;
}

private static Class<?> getDimensionType(Class<?> zlass) {
    while(zlass.isArray()) {
        zlass = zlass.getComponentType();
    }

    return zlass;
}

private static byte type(Type type) {
    if (type == null) {
        return 0;
    } else {
        try {
            return type(Class.forName(type.getTypeName().replaceAll("<.*>", "")));
        } catch (ClassNotFoundException var2) {
            return 0;
        }
    }
}

private static byte type(Class<?> clazz) {
    if (clazz == null) {
        return 0;
    } else if (clazz.isArray()) {
        return 3;
    } else {
        String simpleName = clazz.getSimpleName();
        if (!"List".equals(simpleName) && !"Set".equals(simpleName)) {
            if ("Map".equals(simpleName)) {
                return 2;
            } else {
                Class<?>[] superclass = clazz.getInterfaces();
                Class[] var3 = superclass;
                int var4 = superclass.length;

                for(int var5 = 0; var5 < var4; ++var5) {
                    Class<?> c = var3[var5];
                    simpleName = c.getSimpleName();
                    if ("List".equals(simpleName) || "Set".equals(simpleName)) {
                        return 1;
                    }

                    if ("Map".equals(simpleName)) {
                        return 2;
                    }
                }

                if (clazz.equals(Date.class)) {
                    return 5;
                } else if (clazz.equals(BigDecimal.class)) {
                    return 6;
                } else {
                    return 4;
                }
            }
        } else {
            return 1;
        }
    }
}

private class PooledMap<K, V> {
    private int maxSize;
    private transient volatile List<AirBeanUtils.PooledMap<K, V>.Entry> queue;

    private PooledMap() {
        this.maxSize = 50;
        this.queue = new ArrayList();
    }

    public V get(Object k) {
        Iterator iter = this.queue.iterator();

        AirBeanUtils.PooledMap.Entry type;
        do {
            if (!iter.hasNext()) {
                return null;
            }

            type = (AirBeanUtils.PooledMap.Entry)iter.next();
        } while(type.hash != k.hashCode());

        type.weight++;
        return type.v;
    }

    public V put(K key, V value) {
        if (this.queue.size() >= this.maxSize) {
            AirBeanUtils.PooledMap<K, V>.Entry reObj = null;
            Iterator iter = this.queue.iterator();

            while(iter.hasNext()) {
                AirBeanUtils.PooledMap<K, V>.Entry type = (AirBeanUtils.PooledMap.Entry)iter.next();
                if (reObj == null) {
                    reObj = type;
                } else if (reObj.weight > type.weight) {
                    reObj = type;
                }
            }

            this.queue.remove(reObj);
        }

        this.queue.add(new AirBeanUtils.PooledMap.Entry(key, value));
        return value;
    }

    public boolean containsKey(String k) {
        Iterator iter = this.queue.iterator();

        AirBeanUtils.PooledMap.Entry type;
        do {
            if (!iter.hasNext()) {
                return false;
            }

            type = (AirBeanUtils.PooledMap.Entry)iter.next();
        } while(type.hash != k.hashCode());

        return true;
    }

    private class Entry {
        private int hash;
        private int weight;
        private V v;

        public Entry(K k, V v) {
            this.hash = k.hashCode();
            this.v = v;
        }
    }
}

private class FM {
    Field sfield;
    Field tfield;
    Method setter;
    Method getter;

    private FM() {
    }
}

}

}

package com.pj.handler;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class ClassUtil {

/**
 * 从包package中获取所有的Class
 * @param pack
 * @return
 */
public static Set<Class<?>> getClasses(String pack) {
    // 第一个class类的集合
    Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
    // 是否循环迭代
    boolean recursive = true;
    // 获取包的名字 并进行替换
    String packageName = pack;
    String packageDirName = packageName.replace('.', '/');
    // 定义一个枚举的集合 并进行循环来处理这个目录下的things
    Enumeration<URL> dirs;
    try {
        dirs = Thread.currentThread().getContextClassLoader().getResources(
                packageDirName);
        // 循环迭代下去
        while (dirs.hasMoreElements()) {
            // 获取下一个元素
            URL url = dirs.nextElement();
            // 得到协议的名称
            String protocol = url.getProtocol();
            // 如果是以文件的形式保存在服务器上
            if ("file".equals(protocol)) {
                System.err.println("file类型的扫描");
                // 获取包的物理路径
                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                // 以文件的方式扫描整个包下的文件 并添加到集合中
                findAndAddClassesInPackageByFile(packageName, filePath,
                        recursive, classes);
            } else if ("jar".equals(protocol)) {
                // 如果是jar包文件
                // 定义一个JarFile
                System.err.println("jar类型的扫描");
                JarFile jar;
                try {
                    // 获取jar
                    jar = ((JarURLConnection) url.openConnection())
                            .getJarFile();
                    // 从此jar包 得到一个枚举类
                    Enumeration<JarEntry> entries = jar.entries();
                    // 同样的进行循环迭代
                    while (entries  .hasMoreElements()) {
                        // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
                        JarEntry entry = entries.nextElement();
                        String name = entry.getName();
                        // 如果是以/开头的
                        if (name.charAt(0) == '/') {
                            // 获取后面的字符串
                            name = name.substring(1);
                        }
                        // 如果前半部分和定义的包名相同
                        if (name.startsWith(packageDirName)) {
                            int idx = name.lastIndexOf('/');
                            // 如果以"/"结尾 是一个包
                            if (idx != -1) {
                                // 获取包名 把"/"替换成"."
                                packageName = name.substring(0, idx)
                                        .replace('/', '.');
                            }
                            // 如果可以迭代下去 并且是一个包
                            if ((idx != -1) || recursive) {
                                // 如果是一个.class文件 而且不是目录
                                if (name.endsWith(".class")
                                        && !entry.isDirectory()) {
                                    // 去掉后面的".class" 获取真正的类名
                                    String className = name.substring(
                                            packageName.length() + 1, name
                                                    .length() - 6);
                                    try {
                                        // 添加到classes
                                        classes.add(Class
                                                .forName(packageName + '.'
                                                        + className));
                                    } catch (ClassNotFoundException e) {
                                        // log
                                        // .error("添加用户自定义视图类错误 找不到此类的.class文件");
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    // log.error("在扫描用户定义视图时从jar包获取文件出错");
                    e.printStackTrace();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return classes;
}
/**
 * 以文件的形式来获取包下的所有Class
 * @param packageName
 * @param packagePath
 * @param recursive
 * @param classes
 */
public static void findAndAddClassesInPackageByFile(String packageName,
                                                    String packagePath, final boolean recursive, Set<Class<?>> classes) {
    // 获取此包的目录 建立一个File
    File dir = new File(packagePath);
    // 如果不存在或者 也不是目录就直接返回
    if (!dir.exists() || !dir.isDirectory()) {
        // log.warn("用户定义包名 " + packageName + " 下没有任何文件");
        return;
    }
    // 如果存在 就获取包下的所有文件 包括目录
    File[] dirfiles = dir.listFiles(new FileFilter() {
        // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
        @Override
        public boolean accept(File file) {
            return (recursive && file.isDirectory())
                    || (file.getName().endsWith(".class"));
        }
    });
    // 循环所有文件
    for (File file : dirfiles) {
        // 如果是目录 则继续扫描
        if (file.isDirectory()) {
            findAndAddClassesInPackageByFile(packageName + "."
                            + file.getName(), file.getAbsolutePath(), recursive,
                    classes);
        } else {
            // 如果是java类文件 去掉后面的.class 只留下类名
            String className = file.getName().substring(0,
                    file.getName().length() - 6);
            try {
                // 添加到集合中去
                // classes.add(Class.forName(packageName + '.' +
                // className));
                // 经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
                classes.add(Thread.currentThread().getContextClassLoader()
                        .loadClass(packageName + '.' + className));
            } catch (ClassNotFoundException e) {
                // log.error("添加用户自定义视图类错误 找不到此类的.class文件");
                e.printStackTrace();
            }
        }
    }
}

}

package com.airtimes.mcrsv.localsvr.humanresourceappstructure.utils;

import com.airtimes.mcrsv.data.table.sysuser.ISysUserDao;
import com.airtimes.mcrsv.localsvr.sequence.SequenceService;
import com.airtimes.mcrsv.localsvr.sequence.exception.GlobalSequeceException;
import com.airtimes.mcrsv.localsvr.sequence.exception.TemplateNotFoundException;
import com.airtimes.mcrsv.localsvr.sequence.exception.TemplateStatusException;
import com.airtimes.mcrsv.publics.common.utils.CommonUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Component
public class Utils {

/**
 * 用户dao
 */
@Resource(name = "ISysUserDao")
ISysUserDao userDao;

/**
 * 序列号Service
 */
@Resource
SequenceService sequenceService;

/**
 * 图片url
 */
public static String url;

/**
 * 分页
 *
 * @param list        分页list
 * @param currentPage 页码
 * @param pageSize    条数
 * @return List 分页集合
 */
public <T> List<T> getPageContent(List<T> list, String currentPage, String pageSize) {
    int page = Integer.parseInt(currentPage);
    int size = Integer.parseInt(pageSize);
    // 总记录数
    int total = list.size();
    for (int i = 0; i <= total; i++) {
        // 开始索引
        int fromIndex = (page - 1) * size;
        // 结束索引
        int toIndex = fromIndex + size;
        // 如果结束索引大于集合的最大索引,那么规定结束索引=集合大小
        if (toIndex > total) {
            toIndex = total;
        }
        if (fromIndex <= total) {
            list = list.subList(fromIndex, toIndex);
            if (toIndex >= fromIndex) {
                break;
            }
        }
    }
    return list;
}

/**
 * 时间格式转换
 *
 * @param time
 * @return String 处理后的时间
 */
public String modifyTime(Date time) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return formatter.format(time);
}

/**
 * 时间格式转换
 *
 * @param time
 * @return String 处理后的时间
 */
public String modifyTimeTo(Date time) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    return formatter.format(time);
}

public Date modifyDate(String time)
        throws Exception {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    return formatter.parse(time);
}

/**
 * 时间格式转换
 *
 * @param time yyyy-MM-dd
 * @return String 处理后的时间
 */
public String modifyDayTime(Date time) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    return formatter.format(time);
}

/**
 * 时间格式转换
 *
 * @param time HH:mm
 * @return String 处理后的时间
 */
public String modifyHoueTime(Date time) {
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
    return formatter.format(time);
}

/**
 * 时间格式转换
 *
 * @param time HH:mm
 * @return String 处理后的时间
 */
public Date modifyDateTime(String time)
        throws ParseException {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    if (CommonUtil.isEmpty(time)) {
        return null;
    } else {
        return formatter.parse(time);
    }
}

/*
 * 获取当前天的起始时间
 */
public Date getStartTime(String startDate)
        throws ParseException {
    if (CommonUtil.isEmpty(startDate)) {
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdf.parse(startDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

/*
 * 获取当前天的结束时间
 */
public Date getEndTime(String endDate)
        throws ParseException {
    if (CommonUtil.isEmpty(endDate)) {
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdf.parse(endDate);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}

/**
 * 生成序列号
 *
 * @param seqId 模板id(任务编码:temp_storage_task  问题编号:temp_storage_question)
 * @return 序列号
 * @throws GlobalSequeceException
 * @throws TemplateNotFoundException
 * @throws TemplateStatusException
 */
public String getSequence(String seqId)
        throws GlobalSequeceException, TemplateNotFoundException, TemplateStatusException {
    return sequenceService.generateWithId(seqId);
}

/**
 * 赋值url
 *
 * @param url 图片url
 */
@Value("${fileSystem.url}")
public void setUrl(String url) {
    Utils.url = url;
}

/**
 * isEmpty:判断对象是否为空
 *
 * @param o 对象
 * @return boolean 是否为空
 */
@SuppressWarnings("rawtypes")
public boolean isEmpty(Object o) {
    if (o == null) {
        return true;
    }
    if ((o instanceof String)) {
        if (((String) o).trim().length() == 0) {
            return true;
        }
    } else if ((o instanceof Collection)) {
        if (((Collection) o).isEmpty()) {
            return true;
        }
    } else if (o.getClass().isArray()) {
        if (((Object[]) o).length == 0) {
            return true;
        }
    } else if (((o instanceof Map)) && (((Map) o).isEmpty())) {
        return true;
    }

    return false;
}

/**
 * 计算某时间到现在的年数
 *
 * @param time
 * @return long
 */
public long compareTime(String time) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    Date now1 = new Date();
    String now = sdf.format(now1);
    Date date = null;
    try {
        now1 = sdf.parse(now);
        date = sdf.parse(time);
        start.setTime(date);
        end.setTime(now1);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (end.get(Calendar.YEAR) > start.get(Calendar.YEAR)) {
        int year = end.get(Calendar.YEAR) - start.get(Calendar.YEAR);
        if (end.get(Calendar.MONTH) + 1 > start.get(Calendar.MONTH) + 1) {
            return year;
        } else if (end.get(Calendar.MONTH) + 1 < start.get(Calendar.MONTH) + 1) {
            return year - 1;
        } else {
            if (end.get(Calendar.DATE) >= start.get(Calendar.DATE)) {
                return year;
            } else {
                return year - 1;
            }
        }
    } else {
        return 0;
    }
}

/**
 * 获取几天之后的日期
 *
 * @return
 */
public Date getSpecifiedDayAfter(int days) {
    Calendar c = Calendar.getInstance();
    Date date = new Date();
    c.setTime(date);
    int day = c.get(Calendar.DATE);
    c.set(Calendar.DATE, day + days);
    return c.getTime();
}

/**
 * String 转化为 BigDecimal
 *
 * @return
 */
public BigDecimal stringToBigDecimal(String num) {
    if (CommonUtil.isEmpty(num)) {
        return null;
    }
    return new BigDecimal(num.replaceAll(",", ""));
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值