Chinaunix首页 | 论坛 | 博客
  • 博客访问: 164935
  • 博文数量: 56
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 593
  • 用 户 组: 普通用户
  • 注册时间: 2014-02-18 09:59
文章分类

全部博文(56)

文章存档

2019年(1)

2018年(26)

2016年(1)

2015年(6)

2014年(22)

我的朋友

分类: Java

2014-02-18 10:10:22


点击(此处)折叠或打开

  1. /**
  2.  * @author:      吴永行
  3.  * @dateTime:     2014-1-20 下午9:47:03
  4.  * @description:     
  5.  *
  6.  */
  7. package 深入理解java虚拟机.第九章类加载即执行子系统的案例与实战;

  8. public class ClassModifier {
  9.     private static final int CONSTANT_POOL_COUNT_INDEX = 8;

  10.     private static final int CONSTANT_Utf8_info = 1;

  11.     private static final int[] CONSTANT_ITEM_LENGTH = { -1, -1, 5 - 1, 5, 9, 9,
  12.      3, 3, 5, 5, 5, 5,5 };

  13.     private static final int u1 = 1;
  14.     private static final int u2 = 2;
  15.     private byte[] classByte;

  16.     public ClassModifier(byte[] classByte) {
  17.         this.classByte = classByte;
  18.     }

  19.     public byte[] modifyUTF8Constant(String olderStr, String newStr) {
  20.         int cpc = getConstantPoolCount();
  21.         int offset = CONSTANT_POOL_COUNT_INDEX + u2;
  22.         for (int i = 0; i < cpc; i++) {
  23.             int tag = ByteUtils.bytes2Int(classByte, offset, u1);
  24.             if (tag == CONSTANT_Utf8_info) {
  25.                 int len = ByteUtils.bytes2Int(classByte, offset + u1, u2);
  26.                 offset += (u1 + u2);
  27.                 String str = ByteUtils.bytes2String(classByte, offset, len);
  28.                 if (str.equalsIgnoreCase(olderStr)) {
  29.                     byte[] strBytes = ByteUtils.string2Bytes(newStr);
  30.                     byte[] strLen = ByteUtils.int2Bytes(strBytes.length, u2);
  31.                     classByte = ByteUtils.bytesReplace(classByte, offset - u2,
  32.                      u2, strLen);
  33.                     classByte = ByteUtils.bytesReplace(classByte, offset, len,
  34.                             strBytes);
  35.                     return classByte;
  36.                 } else {
  37.                     offset += len;
  38.                 }

  39.             } else {
  40.                 offset += CONSTANT_ITEM_LENGTH[tag];
  41.             }
  42.         }
  43.         return classByte;
  44.     }

  45.     /**
  46.      * @author:      吴永行
  47.      * @dateTime:     2014-1-20 下午9:53:44
  48.      * @description:     
  49.      * @return
  50.      *
  51.      */
  52.     private int getConstantPoolCount() {

  53.         return ByteUtils.bytes2Int(classByte, CONSTANT_POOL_COUNT_INDEX, u2);
  54.     }
  55. }

阅读(1026) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~