# 一.关键字
# 1.SimpleDateFormat
线程不安全:
/**
* SimpleDateFormat 多线程不安全
*
* @author : kwan
* @date : 2022/8/3
*/
public class Basic_05_SimpleDateFormat_01 extends Thread {
private SimpleDateFormat sdf;
private String dateString;
public Basic_05_SimpleDateFormat_01(SimpleDateFormat sdf, String dateString) {
this.sdf = sdf;
this.dateString = dateString;
}
@Override
public void run() {
try {
Date date = sdf.parse(dateString);
System.out.println(date.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String[] dateStringArray = {"2001-01-01", "2001-01-01", "2001-01-01", "2001-01-01", "2001-01-01"};
Basic_05_SimpleDateFormat_01[] threadArray = new Basic_05_SimpleDateFormat_01[5];
for (int i = 0; i < 5; i++) {
threadArray[i] = new Basic_05_SimpleDateFormat_01(sdf, dateStringArray[i]);
}
for (int i = 0; i < 5; i++) {
threadArray[i].start();
}
}
}
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
每次都创建:
public class Basic_05_SimpleDateFormat_02 extends Thread {
private SimpleDateFormat sdf;
private String dateString;
public Basic_05_SimpleDateFormat_02(SimpleDateFormat sdf, String dateString) {
this.sdf = sdf;
this.dateString = dateString;
}
@Override
public void run() {
try {
Date date = sdf.parse(dateString);
System.out.println(date.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String[] dateStringArray = {"2001-01-01", "2001-01-01", "2001-01-01", "2001-01-01", "2001-01-01"};
Basic_05_SimpleDateFormat_02[] threadArray = new Basic_05_SimpleDateFormat_02[5];
for (int i = 0; i < 5; i++) {
//每次都创建,可以解决线程安全问题
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
threadArray[i] = new Basic_05_SimpleDateFormat_02(sdf, dateStringArray[i]);
}
for (int i = 0; i < 5; i++) {
threadArray[i].start();
}
}
}
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
FastDateFormat:
public class Basic_05_SimpleDateFormat_03 extends Thread {
private FastDateFormat fastDateFormat;
private String dateString;
public Basic_05_SimpleDateFormat_03(FastDateFormat fdf, String dateString) {
this.fastDateFormat = fdf;
this.dateString = dateString;
}
@Override
public void run() {
try {
Date date = fastDateFormat.parse(dateString);
System.out.println(date.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyy-MM-dd");
String[] dateStringArray = {"2001-01-01", "2001-01-01", "2001-01-01", "2001-01-01", "2001-01-01"};
Basic_05_SimpleDateFormat_03[] threadArray = new Basic_05_SimpleDateFormat_03[5];
for (int i = 0; i < 5; i++) {
threadArray[i] = new Basic_05_SimpleDateFormat_03(fastDateFormat, dateStringArray[i]);
}
for (int i = 0; i < 5; i++) {
threadArray[i].start();
}
}
}
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
# 2.finally 总结
# 1.正常返回
/**
* 正常返回值
*
* @author :kwan
* @date :2022/6/16
* 1.与finally相对应的try语句得到执行的情况下,finally才有可能执行。
* 2.finally执行前,程序或线程终止,finally不会执行。
* 3.以后我再也不会说,finally代码块中的代码是一定会执行的代码了。
*/
public class Jvm_book_16_finally_01 {
public static void main(String[] args) {
System.out.println(getNum());
}
//调用该方法返回20
public static int getNum() {
int a = 10;
try {
a = 20;
// a = a/0;
return a;
} catch (Exception e) {
a = 30;
return a;
} finally {
a = 40;
//return a;
}
}
}
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
# 2.返回 finally 的值
/**
* 返回finally的值
*
* @author :kwan
* @date :2022/6/16
*/
public class Jvm_book_16_finally_02 {
public static void main(String[] args) {
System.out.println(getNum());
}
//返回40
public static int getNum() {
int a = 10;
try {
a = 20;
// a = a/0;
return a;
} catch (Exception e) {
a = 30;
return a;
} finally {
a = 40;
return a;
}
}
}
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
# 3.map 中 finally 返回值
/**
* map中finally返回值
*
* @author :kwan
* @date :2022/6/16
*/
public class Jvm_book_16_finally_03 {
public static void main(String[] args) {
System.out.println(getMap().get("name"));
//打印zhaoliu
}
//虽然返回了map,但是值在finally中给修改了,打印zhaoliu
public static Map<String, String> getMap() {
Map<String, String> map = new HashMap<>();
map.put("name", "zhangsan");
try {
map.put("name", "lisi");
return map;
} catch (Exception e) {
map.put("name", "wangwu");
} finally {
map.put("name", "zhaoliu");
map = null;
}
return map;
}
}
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
# 4.try 中 finally 返回值
/**
* try中 finally返回值
*
* @author :kwan
* @date :2022/6/16
*/
public class Jvm_book_16_finally_04 {
public static void main(String[] args) {
System.out.println(getTrue(true));
System.out.println("分界--------->");
System.out.println(getTrue(false));
}
/**
* true
* 分界--------->
* 我是一定会执行的代码?
* true
*/
public static boolean getTrue(boolean flag) {
if (flag) {
return flag;
}
try {
flag = true;
return flag;
} finally {
System.out.println("我是一定会执行的代码?");
}
}
}
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
# 5.异常时 finally 返回值
/**
* 1/0异常时finally返回值
*
* @author :kwan
* @date :2022/6/16
*/
public class Jvm_book_16_finally_05 {
public static void main(String[] args) {
System.out.println(getTrue(true));
System.out.println("分界--------->");
System.out.println(getTrue(false));
}
public static boolean getTrue(boolean flag) {
int i = 1/0;
try {
flag = true;
return flag;
} finally {
System.out.println("我是一定会执行的代码?");
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 6.非正常退出中 finally 返回值
/**
* 非正常退出中finally返回值
*
* @author :kwan
* @date :2022/6/16
*/
public class Jvm_book_16_finally_06 {
public static void main(String[] args) {
System.out.println(getTrue(true));
System.out.println("分界--------->");
System.out.println(getTrue(false));
}
//1.非正常退出 都不打印,控制台为空
//0.正常退出 都不打印,控制台为空
public static boolean getTrue(boolean flag) {
try {
flag = true;
// System.exit(0);
System.exit(1);
return flag;
} finally {
System.out.println("我是一定会执行的代码?");
}
}
}
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
# 7.后台线程中 finally 返回值
/**
* 后台线程中finally返回值
*
* @author :kwan
* @date :2022/6/16
*/
public class Jvm_book_16_finally_07 {
//后台线程t1中有finally块,但在执行前,主线程终止了,导致后台线程立即终止,故finally块无法执行
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(5);
} catch (Exception e) {
} finally {
System.out.println("我是一定会执行的代码?");
}
});
t1.setDaemon(true);//设置t1为后台线程
t1.start();
System.out.println("我是主线程中的代码,主线程是非后台线程。");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 3.isBlank 和 isEmpty
先说总结:isBlank 会判断空白字符串为 null
isEmpty
isEmpty(null)------true isEmpty("")------true isEmpty(" ")------false isEmpty("aa")----false
isBlank(null)------true isBlank(" ")------true isBlank(" ")------true isBlank(" ")------true isBlank("\t \n \f \r")------true //制表符、换行符、换页符和回车符 isBlank("qqqq")------false
isBlank 源码
public static boolean isBlank(String str) {
int strLen;
if (str != null && (strLen = str.length()) != 0) {
for(int i = 0; i < strLen; ++i) {// 判断字符是否为空格、制表符、tab
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
} else {
return true;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
示例
isEmpty判断某字段字符串是否为空,为空的标准是str==null或者str.length()==0
StringUntils.isEmpty(null)=true
StringUntils.isEmpty("")=true
StringUntils.isEmpty(" ")=false
StringUntils.isEmpty("demo")=false
StringUntils.isEmpty(" demo ")=false
isBlank判断某字符串是否为空或长度为0或由空白符构成
StringUtils.isBlank(null)=true
StringUtils.isBlank("")=true
StringUtils.isBlank(" ")=true
StringUtils.isBlank("\t \n \f \r")=true //对于制表符、换行符、换页符合回车符
StringUtils.isBlank()//都识别为空白符
StringUtils.isBlank("\b")=false
StringUtils.isBlank("demo")=false
StringUtils.isBlank(" demo ")=false
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
# 二.实用代码
# 1.mapstruct
# 1.依赖
<!--包含一些核心的注解-->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.3.0.Final</version>
</dependency>
<!--负责生成接口的实现类-->
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.3.0.Final</version>
<scope>compile</scope>
</dependency>
2
3
4
5
6
7
8
9
10
11
12
13
# 2.实体类
@Data
public class Car {
private String make;
private int numberOfSeats;
private CarType type;
//constructor, getters, setters etc.
static enum CarType {
SEDAN
}
}
2
3
4
5
6
7
8
9
10
11
12
13
@Data
public class CarDTO {
private String make;
private int seatCount;
private String type;
}
2
3
4
5
6
7
# 3.接口
@Mapper
public interface CarTransfer {
/**
* 定义个变量,用于获取CarTransfer接口的实现,格式固定如下:
*/
CarTransfer INSTANCE = Mappers.getMapper(CarTransfer.class);
/**
* 当2个类中的字段名不一致时,可以 @Mapping注解来解决,
* source代表源对象中的类,target代表目标
*/
@Mappings(@Mapping(source = "numberOfSeats", target = "seatCount"))
CarDTO toCarDTO(Car car);
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 4.测试
public class Test1 {
public static void main(String[] args) {
Car car = new Car();
car.setMake("car");
car.setNumberOfSeats(1);
car.setType(Car.CarType.SEDAN);
CarDTO carDTO = CarTransfer.INSTANCE.toCarDTO(car);
System.out.println(carDTO);
}
}
2
3
4
5
6
7
8
9
10
11
# 2.枚举示例
@Getter
@AllArgsConstructor
@ApiModel(value = "操作类型", description = "操作类型")
public enum OperateType {
/**
* 新增
*/
INSERT("INSERT", "新增"),
/**
* 更新
*/
UPDATE("UPDATE", "更新"),
/**
* DELETE
*/
DELETE("DELETE", "删除");
private String status;
private String desc;
public static String getDesc(String status) {
for (OperateType statusEnum : OperateType.values()) {
if (statusEnum.getStatus().equals(status)) {
return statusEnum.getDesc();
}
}
return "";
}
}
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
ordinal用法
在 Java 中,所有的枚举类型都继承自 Enum 类。该类提供了一个名为 ordinal()
的方法,用于返回枚举常量在其枚举声明中的位置(从零开始计数)。
enum Color {
RED, GREEN, BLUE
}
2
3
4
则调用
Color.RED.ordinal()
将返回 0,Color.GREEN.ordinal()
将返回 1,Color.BLUE.ordinal()
将返回 2。
需要注意的是,ordinal()
方法通常不是一个好的方式来比较枚举常量的值。因为当枚举顺序发生变化时,它们的 ordinal 值也会随之改变。因此,在大多数情况下,建议使用 equals()
或 ==
运算符来比较枚举常量。
# 3.java 注释引用
java 注释引用另一个类或者枚举
@Data
@ApiModel(value = "Pagination", description = "分页")
public class Pagination<T> {
/**
* @see ExecStatusEnum
*/
@ApiModelProperty(value = "总行数", required = true)
private Long total;
@ApiModelProperty(value = "行数据", required = true)
private List<T> records = new ArrayList<>();
}
2
3
4
5
6
7
8
9
10
11
# 4.线程睡眠
TimeUnit.SECONDS.sleep(100);
# 5.多 catch
//一个try多个catch进行处理
private static void method2() {
try {
int a=10;
int b=5;
int arr[]= {3,1,5};
System.out.println(a/b);
System.out.println(arr[2]);
ArrayList<String>list=new ArrayList<String>();
list.add("hello");
list.add("qwe");
list=null;
for(String s:list) {//对于增强for遍历集合不能为空
System.out.println(s);
}
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("访问了数组不存在的角标");
}catch(ArithmeticException e) {
System.out.println("除数不能为0");
}catch(Exception d) {
System.out.println("程序出问题了");
}
System.out.println("over");
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 6.单独引入 slf4j 注解
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.28</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.28</version>
</dependency>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 7.获取客户端 ip
private static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
String ipSeparate = ",";
int ipLength = 15;
if (ip != null && ip.length() > ipLength) {
if (ip.indexOf(ipSeparate) > 0) {
ip = ip.substring(0, ip.indexOf(ipSeparate));
}
}
if (StringUtils.isNotBlank(ip)) {
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
return "";
}
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
# 8.UuidUtil 使用
public final class UuidUtil {
/**
* uuid生成
*/
public static String getUuid() {
return UUID.randomUUID().toString().replace("-", "");
}
}
2
3
4
5
6
7
8
# 9.aop 保存操作日志
package com.deepexi.dct.manager.service.Log;
import com.alibaba.fastjson.JSON;
import com.deepexi.dct.manager.api.dto.TaskDto;
import com.deepexi.dct.manager.enums.OperateType;
import com.deepexi.dct.manager.logs.anotation.LogAnno;
import com.deepexi.dct.manager.logs.entity.Logs;
import com.deepexi.dct.manager.logs.service.LogsService;
import com.deepexi.dct.manager.logs.utils.DateUtils;
import com.deepexi.dct.manager.service.security.AppRuntimeEnv;
import com.deepexi.dct.manager.utils.StringUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.*;
@Api(tags = "日志记录")
@Aspect
@Component
@Slf4j
public class LogAopAspect {
@Autowired
private LogsService LogsService;
@Autowired
private AppRuntimeEnv appRuntimeEnv;
/**
* 环绕通知记录日志通过注解匹配到需要增加日志功能的方法
*/
@Around("@annotation(com.deepexi.dct.manager.logs.anotation.LogAnno)")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (Objects.isNull(attributes)) {
pjp.proceed();
return null;
}
HttpServletRequest request = attributes.getRequest();
// 1.方法执行前的处理,相当于前置通知
MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
// 获取方法
Method method = methodSignature.getMethod();
// 获取方法上面的注解
LogAnno logAnno = method.getAnnotation(LogAnno.class);
log.info("Request IP" + getIp(request));
log.info("Request URL: " + request.getRequestURL().toString());
Enumeration<String> enums = request.getParameterNames();
Logs logs = new Logs();
logs.setOperateorIp(getIp(request));//todo:获取的方式是有问题的bug
logs.setOperateUrl(request.getRequestURI());
logs.setOperateor(appRuntimeEnv.getUsername());// 设置操作人
logs.setTenantId(appRuntimeEnv.getTenantId());
logs.setCreatedBy(appRuntimeEnv.getUsername());
logs.setUpdatedBy(appRuntimeEnv.getUsername());
logs.setOperateType(OperateType.getDesc(logAnno.operateType()));//操作类型
Map<String, Object> map = getNameAndValue(pjp);
logs.setOperateInfo("操作模块[" + logAnno.module() + "]" + "\n"
+ "操作描述[" + logAnno.description() + "]" + "\n"
+ "操作内容[" + JSON.toJSONString(map) + "]"
// + "操作方法[" + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName() + "] "
);
Object result;
this.setTaskId(logAnno, logs, map);
try {
//让代理方法执行
result = pjp.proceed();
// 2.相当于后置通知(方法成功执行之后走这里)
logs.setOperateResult("正常");// 设置操作结果
} catch (Exception e) {
// 3.相当于异常通知部分
logs.setOperateResult("失败");// 设置操作结果
throw e;
} finally {
// 4.相当于最终通知
logs.setCreatedAt(DateUtils.getTimestamp(new Date()));// 设置操作日期
LogsService.addLog(logs);// 添加日志记录
}
return result;
}
//设置taskId
private void setTaskId(LogAnno logAnno, Logs logs, Map<String, Object> map) {
if (logAnno.module().equalsIgnoreCase("任务模块")) {
map.keySet().forEach(e -> {
if (e.equalsIgnoreCase("taskDto")) {
TaskDto taskDto = (TaskDto) map.get(e);
logs.setTaskId(taskDto.getId());
}
});
} else {
if (map.containsKey("taskId") && StringUtils.isNotBlank(map.get("taskId").toString()))
logs.setTaskId(map.get("taskId").toString());
}
}
/**
* 获取参数Map集合
*/
Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
Map<String, Object> param = new HashMap<>();
Object[] paramValues = joinPoint.getArgs();
String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
if (paramNames == null) {
return param;
}
for (int i = 0; i < paramNames.length; i++) {
param.put(paramNames[i], paramValues[i]);
}
return param;
}
}
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
# 10.获取客户端 ip
private static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
//对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
String ipSeparate = ",";
int ipLength = 15;
if (ip != null && ip.length() > ipLength) {
if (ip.indexOf(ipSeparate) > 0) {
ip = ip.substring(0, ip.indexOf(ipSeparate));
}
}
if (StringUtils.isNotBlank(ip)) {
return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
return "";
}
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
# 11.注解引用别的类
java 注释引用另一个类或者枚举
@Data
@ApiModel(value = "Pagination", description = "分页")
public class Pagination<T> {
/**
* @see ExecStatusEnum
*/
@ApiModelProperty(value = "总行数", required = true)
private Long total;
@ApiModelProperty(value = "行数据", required = true)
private List<T> records = new ArrayList<>();
public Pagination() {
}
public Pagination(Long total, List<T> rows) {
this.total = total;
this.records = rows;
}
public Pagination(Long total, List<T> rows, Integer pagesize, Integer pageno) {
this.total = total;
this.records = rows;
}
public static <T> Pagination<T> from(Page<T> page) {
return new Pagination<>(page.getTotal(), page.getRecords());
}
public static <T> Pagination<T> from(Long total, List<T> rows) {
return new Pagination<>(total, rows);
}
public static <T> Pagination<T> from(Long total, List<T> rows, Integer pagesize, Integer pageno) {
return new Pagination<>(total, rows, pagesize, pageno);
}
}
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
# 12.map 转对象
在使用 BeanUtils.populate()
方法将一个 Map 中的数据封装进一个 JavaBean 对象时,需要注意一些问题。
首先,BeanUtils.populate()
方法会根据 Map 中的 key 值来匹配 JavaBean 对象中的属性名。如果 Map 中的 key 值与 JavaBean 对象的属性名不一致,那么该属性就不会被设置。因此,在使用 BeanUtils.populate()
方法时,需要确保 Map 中的 key 值与 JavaBean 对象的属性名一致。
其次,JavaBean 对象的属性类型需要与 Map 中的 value 值类型相匹配。如果不匹配,那么就会出现类型转换异常。例如,如果 JavaBean 对象的某个属性是一个 int
类型,而 Map 中对应的 value 值是一个 String
类型,那么就会出现类型转换异常。
最后,需要确保 JavaBean 对象中的属性都有相应的 setter 方法。如果没有相应的 setter 方法,那么无法通过 BeanUtils.populate()
方法来设置该属性的值。
如果 BeanUtils.populate()
方法无法将 Map 中的数据封装进 JavaBean 对象中,可能是由于以上原因导致的。可以检查一下 Map 中的 key 值是否与 JavaBean 对象的属性名一致,以及属性类型和 setter 方法是否正确。如果还有其他问题,可以考虑使用其他的工具类来进行数据的封装。
# 13.发邮件
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
2
3
4
5
public class Basic_07_Email {
public static void main(String[] args) throws InterruptedException {
SimpleEmail email = new SimpleEmail();
//qq:qq邮件服务器的端口号
email.setSslSmtpPort("465");
email.setHostName("smtp.qq.com");
email.setAuthentication("327782001@qq.com", "xspjrhivsncybjjf");
email.setCharset("UTF-8");
try {
email.addTo("3327782001@qq.com");
email.setFrom("327782001@qq.com");
email.setSubject("标题");
email.setMsg("内容----->>>>>>>>>");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 14.Holder
参数的传递:
public class Test {
public static void main(String[] args) {
Holder<String> holder = new Holder<>();
holder.value = "你好";
change(holder);
System.out.println(holder.value);
}
public static void change(Holder<String> holder) {
holder.value = "Hello World!";
}
}
2
3
4
5
6
7
8
9
10
11
12
← 04-JDK新特性 06-JavaWeb →