工作中的小玩意~~
流程:
- 註解實現
- 反射工具類
註解定義及實現
註解定義:
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckParam {
String value() default "-1";
}
簡單解釋上述其相關注解
Target:描述了註解修飾的對象範圍,取值在java.lang.annotation.ElementType
定義,常用的包括:
CONSTRUCTOR
: 用於描述構造器FIELD
: 用於描述域LOCAL_VARIABLE
: 用於描述局部變量METHOD
: 用於描述方法PACKAGE
: 用於描述包PARAMETER
: 用於描述參數TYPE
: 用於描述類、接口(包括註解類型) 或enum
聲明
Retention: 表示註解保留時間長短。取值在java.lang.annotation.RetentionPolicy
中,取值爲:
SOURCE
:在源文件中有效,編譯過程中會被忽略CLASS
:隨源文件一起編譯在class
文件中,運行時忽略RUNTIME
:在運行時有效(大部分註解的選擇)
這裏我們的目的是爲了實現對對象屬性的判空賦值,所以Target
選擇的修飾的範圍是FIELD
,運行週期在運行時有效。
創建對應實體:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Sample{
@CheckParam
private String id;
@CheckParam
private String name;
}
反射工具類實現
反射之所以被稱爲框架的靈魂,主要是因爲它賦予了我們在運行時分析類以及執行類中方法的能力。通過反射可以獲取任意一個類的所有屬性和方法,你還可以調用這些方法和屬性。
反射的具體使用:https://www.cnblogs.com/xbhog/p/14987005.html
通過與註解的搭配,我們可以實現在運行期中獲取目標對象的屬性進行判斷及賦值。
工具類的實現流程:
- 獲取操作對象,即傳入的類對象
- 獲得對象中所有的屬性
- 開啓私有的屬性的訪問權限
- 前置校驗(是否被自定義註解修飾過)
- 實現目的:屬性爲空,則賦值(判空賦值)
代碼實現:
package com.example.containstest.containsTestDemo.utils;
import com.example.containstest.containsTestDemo.annotation.CheckParam;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
* @author xbhog
* @describe:
* @date 2023/5/11
*/
public class ChecFieldkUtil {
public static <T> void checkParamsFiled(T t) throws RuntimeException, IllegalAccessException {
if (null == t) {
throw new RuntimeException("obj is null");
}
//獲取class對象
Class<?> aClass = t.getClass();
//獲取當前對象所有屬性 使用帶Declared的方法可訪問private屬性
Field[] declaredFields = aClass.getDeclaredFields();
//遍歷對象屬性
for (Field field : declaredFields) {
//開啓訪問權限
field.setAccessible(true);
//使用此方法 field.get(Object obj) 可以獲取 當前對象這個列的值
Object o = field.get(t);
CheckParam annotation = field.getDeclaredAnnotation(CheckParam.class);
//如果沒有設置當前註解 不用校驗
if (annotation == null) {
continue;
}
//獲取註解接口對象
//如果設置了當前註解,但是沒有值,拋出異常
if (o == null || StringUtils.isBlank(ObjectUtils.toString(o))) {
System.out.println("========"+ annotation.value());
field.set(t,annotation.value());
}
}
}
}
實現效果:
/**
* @author xbhog
* @describe:
* @date 2023/5/11
*/
public class TestClass511 {
@Test
public void demo12() throws IllegalAccessException {
Sample sample = new Sample();
CheckUtil.checkUserFiled(sample);
System.out.println(sample.getName());
}
}