zhanghua
2023-03-20 2d1d03a0d5c8abbe721524d39f7772633064577b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package com.ycl.common.util;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class CommonUtils {
    /**
     * 检查对象是否为空
     * 
     * @param obj
     *            java任意类型
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
 
        } else if (obj instanceof String && (obj.toString().trim().equals(""))) {
            return true;
 
        } else if (obj instanceof Number && ((Number) obj).doubleValue() < 0) {
            return true;
 
        } else if (obj instanceof Collection && ((Collection) obj).isEmpty()) {
            return true;
 
        } else if (obj instanceof Map && ((Map) obj).isEmpty()) {
            return true;
 
        } else if (obj instanceof Object[] && ((Object[]) obj).length == 0) {
            return true;
 
        }
        return false;
    }
 
    /**
     * 检查n个对象是否为空
     * 
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object... obj) {
        boolean res = false;
        for (Object o : obj) {
            if (isEmpty(o)) {
                res = true;
                break;
            }
        }
        return res;
    }
 
    /**
     * 
     * 
     * @param obj
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static boolean hasLength(Object obj, int length) {
 
        if (obj == null) {
            return false;
 
        } else if (obj instanceof String) {
            return obj.toString().trim().length() == length;
 
        } else if (obj instanceof Collection) {
            return ((Collection) obj).size() == length;
 
        } else if (obj instanceof Map) {
            return ((Map) obj).size() == length;
 
        } else if (obj instanceof Object[]) {
            return ((Object[]) obj).length == length;
 
        }
 
        return false;
 
    }
 
    /**
     * 检查对象是否不为空
     * 
     * @param obj
     * @return
     */
    public static boolean isNotEmpty(Object obj) {
        return !isEmpty(obj);
    }
 
    /**
     * 检查对象是否不为空
     * 
     * @param obj
     * @return
     */
    public static boolean isNotEmpty(Object... obj) {
        boolean res = true;
        for (Object o : obj) {
            if (isEmpty(o)) {
                res = false;
            }
        }
        return res;
    }
 
 
 
    /**
     * 克隆一个对象
     * 
     * @param obj
     * @return
     * @throws Exception
     */
    public static Object cloneObject(Object obj) throws Exception {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteOut);
        out.writeObject(obj);
        ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
        ObjectInputStream in = new ObjectInputStream(byteIn);
        return in.readObject();
    }
 
    /**
     * 判断是否为中文
     * 
     * @param c
     * @return
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }
 
    public static boolean isChinese(String str) {
        if (null != str && str.length() > 0) {
            char[] chares = str.toCharArray();
            for (char c : chares) {
                if (isChinese(c))
                    return true;
            }
        } else
            return false;
 
        return false;
    }
 
    /**
     * 判断是否为中文乱码
     * 
     * @param strName
     * @return
     */
    public static boolean hasMessyCode(String target) {
        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
        Matcher m = p.matcher(target);
        String after = m.replaceAll("");
        String temp = after.replaceAll("}", "");
        char[] ch = temp.trim().toCharArray();
        float chLength = ch.length;
        float count = 0;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (!Character.isLetterOrDigit(c)) {
 
                if (!isChinese(c)) {
                    count = count + 1;
                }
            }
        }
        float result = count / chLength;
        if (result > 0.4) {
            return true;
        } else {
            return false;
        }
    }
 
    /**
     * 生成N位随机数
     * 
     * @return
     */
    public static String getRandom(int N) {
        int[] rand = new int[N];
        StringBuffer numString = new StringBuffer();
        for (int i = 0; i < rand.length; i++) {
            rand[i] = (Integer) new Random().nextInt(9);
            numString.append(rand[i]);
        }
        return numString.toString();
    }
 
    /**
     * 同类对象属性复制(private,public) 复制出来的为新对象
     * 
     * @param object
     * @return
     * @throws Exception
     */
    public static Object copyThisToNewOne(Object object) throws Exception {
        Class<?> classType = object.getClass();
        Object obj = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
        Field[] fields = classType.getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isPrivate(field.getModifiers())) {// 只需要私有字段
                String name = field.getName();
                String firstLetter = name.substring(0, 1).toUpperCase();
                String getMethodName = "get" + firstLetter + name.substring(1);
                String setMethodName = "set" + firstLetter + name.substring(1);
                Method getMethod = classType.getMethod(getMethodName, new Class[] {});
                Method setMethod = classType.getMethod(setMethodName, new Class[] { field.getType() });
                Object value = getMethod.invoke(object, new Object[] {});
                if (value != null) {
                    setMethod.invoke(obj, new Object[] { value });
                }
            } else {
                // System.out.println(field.get(object));
                obj.getClass().getField(field.getName()).set((Object) obj, field.get(object));
            }
        }
        return obj;
    }
 
    /**
     * 同类对象属性复制(private,public) 把2个已有的对象属性进行复制 此方法src代表来源数据对象,
     * result代表要把src中的属性复制到的对象
     * 
     * @param object
     * @return
     * @throws Exception
     */
    public static Object copyThisToAnother(Object src, Object result) throws Exception {
        Class<?> classType = src.getClass();
        Object obj = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});
        Field[] fields = classType.getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isPrivate(field.getModifiers())) {// 只需要私有字段
                String name = field.getName();
                String firstLetter = name.substring(0, 1).toUpperCase();
                String getMethodName = "get" + firstLetter + name.substring(1);
                String setMethodName = "set" + firstLetter + name.substring(1);
                Method getMethod = classType.getMethod(getMethodName, new Class[] {});
                Method setMethod = classType.getMethod(setMethodName, new Class[] { field.getType() });
                Object value = getMethod.invoke(src, new Object[] {});
                if (value != null) {
                    setMethod.invoke(result, new Object[] { value });
                }
            } else {
                // System.out.println(field.get(src));
                obj.getClass().getField(field.getName()).set(result, field.get(src));
            }
        }
        return result;
    }
 
    public static String getRandomString(int length) { // length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
 
    public static String getUpperStringRandom(int length) { // length表示生成字符串的长度
 
        return getRandomString(length).toUpperCase();
    }
 
    /**
     * 数字随机码码
     * 
     * @param length
     * @return
     */
    public static String getDigitRandom(int length) { // length表示生成字符串的长度
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
 
    public static String getFormatParam(Object... obj) { // length表示生成字符串的长度
 
        StringBuffer sb = new StringBuffer();
        for (Object o : obj) {
            if (CommonUtils.isEmpty(sb.toString()))
                sb.append(o.toString());
            else
                sb.append("," + o.toString());
 
        }
        return sb.toString();
    }
 
    /**
     * 获取一个时间格式的编号
     * 
     * @param random
     * @return yyyyMMddHHmmss + random(bit)
     */
    public static String getIdentityByTime(int random) {
 
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        return dateFormat.format(date) + getDigitRandom(random);
    }
 
    public static String getUUID(boolean hasSplit) {
        UUID uuid = UUID.randomUUID();
        return hasSplit ? uuid.toString() : uuid.toString().replace("-", "");
    }
 
    public static <T> List<T> removeNull(List<? extends T> oldList) {
        oldList.removeAll(Collections.singleton(null));
          Iterator  iterator =   oldList.iterator();
        while (iterator.hasNext()) {
            if (checkIsEtmy(iterator.next())) {
                iterator.remove();
            }
        }
        return (List<T>) oldList;
    }
 
    public static boolean checkIsEtmy(Object o) {
         boolean flag = true;
        //获取参数类
        Class cls = o.getClass();
        //将参数类转换为对应属性数量的Field类型数组(即该类有多少个属性字段 N 转换后的数组长度即为 N)
        Field[] fields = cls.getDeclaredFields();
        for(int i = 0;i < fields.length; i ++){
            Field f = fields[i];
            f.setAccessible(true);
            //f.getName()得到对应字段的属性名,f.get(o)得到对应字段属性值,f.getGenericType()得到对应字段的类型
            try {
                if (f.get(o)!=null&&!"".equals(f.get(o).toString())) {
                    flag = false;
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return flag;
    }
}