遗留问题——transient关键字的使用

在通过反射列出一个对象的所有域的字符串形式的测试中,在对结果的比较过程中,遇到了这个关键词修饰的域,有时间再好好研究一下:

public class ObjectAnalyzer {

	private ArrayList<Object> visited = new ArrayList<>();
	
	/**
	 *  将对象转换为 列出所有域的字符串形式
	 * @param obj 一个对象
	 * @return 包含对象的类名和所有域名和值 的字符串
	 */
	public String toString(Object obj)
	{
		if(obj == null)
			return "null";
		if(visited.contains(obj))
			return "...";
		visited.add(obj);
		Class c1 = obj.getClass();
		if(c1 == String.class)
			return (String)obj;
		if(c1.isArray())
		{
			//component--n:组成部分; 成分; 部件;adj:成分的; 组成的; 合成的; 构成的;
			//getComponentType()返回数组中元素的Class对象,如果不是Class对象那么返回null
			String r = "falg" + c1.getComponentType() + "[]{ArrayList中的object数组:";
			for(int i = 0;i < Array.getLength(obj); i++) {
				if(i > 0)
					r += ",";
				Object val = Array.get(obj, i);
				if(c1.getComponentType().isPrimitive())
					r += val;
				else 
					r += toString(val);
			}
			return r + "数组遍历完毕}";
		}
		
		String r = c1.getName();
		do {
			r += "[";
			Field[] fields = c1.getDeclaredFields();
			AccessibleObject.setAccessible(fields, true);//获得访问控制权限,否则下面的get方法将会抛出一个illegalAccessException
			//获取所有域的名字和值(即属性名和属性值)
			for(Field field : fields)
			{
				if(!Modifier.isStatic(field.getModifiers())) {//如果域不是静态的——————多打的两个空是父类的域,但是是空的
					if(!r.endsWith("["))					  //不是刚开始,加分隔符“,”
						r += ",";
					r += field.getName() + "=";
					try {
						Class t = field.getType();			  //获取域的类型
						Object val = field.get(obj);		  //获取拥有这个域的对象的值
						if(t.isPrimitive())					  //如果域的类型是基本数据类型(八大基本类型)
							r += val;
						else
							r += toString(val);				  //基本数据类型需要强转
					} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
					}
				}
			}
			if(r.endsWith("["))
				r += "父类被过滤的静态域";
			r += "]";
			c1 = c1.getSuperclass();						//再获取父类的域信息
		}while(c1 != null);
		return r;
		
	}
	public static void main(String[] args) {
		ReflectionTest test = new ReflectionTest();
		ArrayList<Integer> squares = new ArrayList<>();
		for(int i = 1; i <= 5; i++) {
			squares.add(i * i);
		}
		//System.out.println(Object.class.getSuperclass().getName());
		String str = "hello world!";
		Object aObject = str;
		System.out.println(aObject.getClass().getComponentType());
		System.out.println(new ObjectAnalyzer().toString(squares));
	}
}

null
java.util.ArrayList[elementData=falgclass java.lang.Object[]{ArrayList中的object数组:java.lang.Integer[value=1][父类被过滤的静态域][父类被过滤的静态域],java.lang.Integer[value=4][父类被过滤的静态域][父类被过滤的静态域],java.lang.Integer[value=9][父类被过滤的静态域][父类被过滤的静态域],java.lang.Integer[value=16][父类被过滤的静态域][父类被过滤的静态域],java.lang.Integer[value=25][父类被过滤的静态域][父类被过滤的静态域],null,null,null,null,null数组遍历完毕},size=5][modCount=5][父类被过滤的静态域][父类被过滤的静态域]
 

    ArrayList中
    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access
    在抽象类AbstractList中发现
    /**
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     *
     * <p>This field is used by the iterator and list iterator implementation
     * returned by the {@code iterator} and {@code listIterator} methods.
     * If the value of this field changes unexpectedly, the iterator (or list
     * iterator) will throw a {@code ConcurrentModificationException} in
     * response to the {@code next}, {@code remove}, {@code previous},
     * {@code set} or {@code add} operations.  This provides
     * <i>fail-fast</i> behavior, rather than non-deterministic behavior in
     * the face of concurrent modification during iteration.
     *
     * <p><b>Use of this field by subclasses is optional.</b> If a subclass
     * wishes to provide fail-fast iterators (and list iterators), then it
     * merely has to increment this field in its {@code add(int, E)} and
     * {@code remove(int)} methods (and any other methods that it overrides
     * that result in structural modifications to the list).  A single call to
     * {@code add(int, E)} or {@code remove(int)} must add no more than
     * one to this field, or the iterators (and list iterators) will throw
     * bogus {@code ConcurrentModificationExceptions}.  If an implementation
     * does not wish to provide fail-fast iterators, this field may be
     * ignored.
     */
    protected transient int modCount = 0;

参考

后记:这个关键字是为了不被序列化定义的,在序列化反序列化传输的时候,不会序列化它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值