反射获取hashMap
反射是基于hashmap内部实现原理,Hashmap的核心在putval方法和内部类Node的组成.
核心方法putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
可以看到hashmap由Node对象构成基础,那么我们反射的时候就要想法设法的把它的node给搞出来
Node构成
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
node由hash,key,value,next这几个构成,他们都为属性名,那么就是可以通过反射获取到的。
反射的实现
//o 就是一个hash数组 里面有{code,msg,data}
private Object GetHashTableValue(Object o){
Object resObj = new Object();
//定义hashmap
Class clsHashMap = null;
//定义hashmap里的Node
Class clsHashMap$Node = null;
Field[] f = null;
Field t = null, fNode = null;
try {
clsHashMap = Class.forName("java.util.HashMap");
clsHashMap$Node = Class.forName("java.util.HashMap$Node");
// 获取hashmap里的全部属性
//里面有serialVersionUID,DEFAULT_INITIAL_CAPACITY,MAXIMUM_CAPACITY,DEFAULT_LOAD_FACTOR,TREEIFY_THRESHOLD,UNTREEIFY_THRESHOLD,MIN_TREEIFY_CAPACITY,
f = clsHashMap.getDeclaredFields();
AccessibleObject.setAccessible(f, true);
for (Field field : f) {
// System.out.println(field.getName());
//获取属性名为table的,然后赋值给 filed
if (field.getName() == "table")
t = field;
}
//这这里的t为tree transient Node<K,V>[] table; 由此可见这个是一个数组,所以要Object[] 来转换下
//注:如果是继承hashmap那么继承的属性也会在这里面。比如有个getmes类,其中有code,msg属性,那么o1也会有
Object[] o1 = ((Object[]) t.get(o));
//这里面遍历的便是node
for (Object o2 : o1) {
if (o2!=null){
Object next = o2;//这个next就相当于是node一个类
while (next!=null){
//反射value属性
Field value = clsHashMap$Node.getDeclaredField("value");
//反射next属性
Field o_next = clsHashMap$Node.getDeclaredField("next");
//根据自己需要还可以反射key和hash,方法一样
o_next.setAccessible(true);
value.setAccessible(true);
//得到value值
resObj = value.get(next);
//得到下个节点node 可以赋值给fNode
Object objNext = o_next.get(next);
next = objNext;
}
}
}
} catch (ClassNotFoundException | IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
return resObj;
}
可以看到hashmap有大量的属性
transient Node<K,V>[] table;
private static final long serialVersionUID = 362498820763181265L;
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
int threshold;
final float loadFactor;
注:transient是短暂的意思。对于transient 修饰的成员变量,在类的实例对象的序列化处理过程中会被忽略。 因此,transient变量不会贯穿对象的序列化和反序列化,生命周期仅存于调用者的内存中而不会写到磁盘里进行持久化
总结:
反射hashmap核心还是反射其中hashmap的内部类node类,只要拿的到它,就能反射相应的元素