01: /*
02: * Copyright (C) 2007 XStream Committers.
03: * All rights reserved.
04: *
05: * The software in this package is published under the terms of the BSD
06: * style license a copy of which has been included with this distribution in
07: * the LICENSE.txt file.
08: *
09: * Created on 17. May 2007 by Joerg Schaible
10: */
11: package com.thoughtworks.xstream.converters.reflection;
12:
13: import com.thoughtworks.xstream.core.util.OrderRetainingMap;
14:
15: import junit.framework.TestCase;
16:
17: import java.lang.reflect.Field;
18: import java.util.Map;
19:
20: public class NativeFieldKeySorterTest extends TestCase {
21:
22: static class Base {
23: String yyy;
24: String ccc;
25: String bbb;
26: }
27:
28: static class First extends Base {
29: String aaa;
30: }
31:
32: static class Second extends First {
33: String xxx;
34: String zzz;
35: }
36:
37: public void testDoesSortInDeclarationOrderWithFieldsOfBaseClassFirst() {
38: String[] fieldOrder = new String[] { "yyy", "ccc", "bbb",
39: "aaa", "xxx", "zzz" };
40: FieldKeySorter sorter = new NativeFieldKeySorter();
41: Map originalMap = buildMap(Second.class);
42: Map map = sorter.sort(Second.class, originalMap);
43: Field[] fields = (Field[]) map.values().toArray(
44: new Field[map.size()]);
45: assertEquals(fieldOrder.length, fields.length);
46: for (int i = 0; i < fieldOrder.length; i++) {
47: assertEquals("Field[" + i + ']', fieldOrder[i], fields[i]
48: .getName());
49: }
50: }
51:
52: private Map buildMap(Class type) {
53: Map map = new OrderRetainingMap();
54: Class cls = type;
55: while (!cls.equals(Object.class)) {
56: Field[] fields = cls.getDeclaredFields();
57: for (int i = 0; i < fields.length; i++) {
58: Field field = fields[i];
59: map.put(new FieldKey(field.getName(), cls, i), field);
60: }
61: cls = cls.getSuperclass();
62: }
63: return map;
64: }
65: }
|