溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java注解之運行時修改字段的注解值操作

發(fā)布時間:2020-08-30 19:22:20 來源:腳本之家 閱讀:598 作者:藍色土耳其18 欄目:開發(fā)技術

今天遇到需求:導入Excel時候列頭會發(fā)生變化,客戶是大爺要求你改代碼,

導入Excel是用easypoi做的,識別表頭是用注解@Excel(name = "xxx")通過這個name來匹配

那你表頭要動,我這個注解是硬編碼

所以就有動態(tài)設置這個表頭

public class JavaVo{
@Excel(name = "xxx")
private String userName;
//省略getset方法
}

ExcelImportUtil.importExcel(file.getInputStream(), configClass(JavaVo.class), params);

代碼如下

 private Class configClass(Class c , String val) {
   
   Field[] fields = c.getDeclaredFields();
   try {
  for(int i = 0;i < fields.length;i++){
  Field f = fields[i];
  Excel excelAn = f.getAnnotation(Excel.class);//Excel是注解類型
  if(excelAn == null){
   continue;
  }
  InvocationHandler h = Proxy.getInvocationHandler(excelAn);
  Field hField = h.getClass().getDeclaredField("memberValues");
    // 因為這個字段事 private final 修飾,所以要打開權限
    hField.setAccessible(true);
    // 獲取 memberValues
    Map memberValues = (Map) hField.get(h);
    // 修改 value 屬性值 這里修改的是@Excel(name = "姓名")
        //name是key
    memberValues.put("name", val);
  }
 } catch (Exception e) {
  e.printStackTrace();
 }
 return c;
 }

補充知識:java動態(tài)修改 注解的值,控制對象轉化為json字符串的字段是否序列化

定義一個對象使用@JSONField控制該對象屬性是否需要序列化

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;

@Data
public class A {
  @JSONField(serialize = false)
  private String extendParams;

  @JSONField(serialize = true)
  private String sad;
}

編寫工具類

import com.alibaba.fastjson.annotation.JSONField;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;
import lombok.val;

/**
 * 動態(tài)操作注解屬性
 * @since 2020年8月13日20:49:26
 */
public class AnnotationUtils<T> {
  /**
   * 查看注解屬性
   * @param t
   * @param name
   * @return
   * @throws NoSuchFieldException
   */
  public Object getJSONFieldProp(T t, String name) throws NoSuchFieldException {
    Field field = t.getClass().getDeclaredField(name);
    JSONField annotation = field.getAnnotation(JSONField.class);
    val serialize = annotation.serialize();
    return serialize;
  }

  /**
   * 修改注解屬性
   * @param t
   * @param value
   * @return
   * @throws NoSuchFieldException
   * @throws IllegalAccessException
   */
  public Object setJSONFieldProp(T t,String name, Object value) throws NoSuchFieldException, IllegalAccessException {
    Field field = t.getClass().getDeclaredField(name);
    JSONField annotation = field.getAnnotation(JSONField.class);
    InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
    Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
    memberValues.setAccessible(true);
    Map map = (Map) memberValues.get(invocationHandler);
    map.put("serialize",value);
    val serialize = annotation.serialize();
    return serialize;
  }
}

測試

import com.alibaba.fastjson.JSON;

public class TT {

  public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    AnnotationUtils<A> aAnnotationUtils = new AnnotationUtils<>();
    A a = new A();
    a.setExtendParams("exex");
    a.setSad("sadsad");

    Object extendParams = aAnnotationUtils.getJSONFieldProp(a, "extendParams");//查詢注解的值
    System.out.println(extendParams.toString());
//    System.out.println(JSON.toJSONString(a));

    Object extendParams1 = aAnnotationUtils.setJSONFieldProp(a, "extendParams", true);//修改注解的值
    System.out.println(extendParams1.toString());
    System.out.println(JSON.toJSONString(a));
  }
}

去掉main里面的注解看看效果,這個好像是發(fā)生了jvm優(yōu)化導致的問題。。。

注釋第一個print 打印結果如下:

false
true
{"extendParams":"exex","sad":"sadsad"}

不注釋第一個print 打印結果如下:

false
{"sad":"sadsad"}
true
{"sad":"sadsad"}

接下來我們在做一個測試

  public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    List<A> aList = new ArrayList<>();
    for(int i=0; i<10; i++){
      AnnotationUtils<A> aAnnotationUtils = new AnnotationUtils<>();
      A a = new A();
      a.setExtendParams("exex");
      a.setSad("sadsad");
      if(i%2 == 0) {
        aAnnotationUtils.setJSONFieldProp(a, "extendParams", true);//修改注解的值
      }
      aList.add(a);
    }
    System.out.println(JSON.toJSONString(aList));
  }

打印結果

[{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"},{"extendParams":"exex","sad":"sadsad"}]

我本想用修改注解的方式來修改某個字段的序列化與不序列化,但是我發(fā)現(xiàn)注解是在class層面的并不是在對象層面。所以我的設想失敗了。。

以上這篇java注解之運行時修改字段的注解值操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI