[英]How to access the object value with java.util.LinkedHashMap$EntryIterator type
I need to access the value for the field called this$0 of object type java.util.LinkedHashMap$EntryIterator type, see the image below. 我需要访问对象类型java.util.LinkedHashMap $ EntryIterator类型的this $ 0字段的值,请参见下图。
the object 物体
Iterator<Entry<String, JsonNode>> ite = data.getFields();
as you can see, I have a object "ite" and I need to access the value of field "this$0" , how to get it? 如您所见,我有一个对象“ ite”,我需要访问字段“ this $ 0”的值,如何获取它?
This field is added by compiler to store in inner class reference to its outer class (when inner class is not static). 编译器添加了此字段,以在内部类中存储对其外部类的引用(当内部类不是静态的时)。 Thanks to this field inner class instance has access to members (even private ones) of outer class instance.
由于有了这个字段,内部类实例可以访问外部类实例的成员(甚至是私有成员)。
Value of this field is set by outerClassInstance.new InnerClass()
so this$0
in InnerClass
instance will contain same value as outerClassInstance
reference. 该字段的值由
outerClassInstance.new InnerClass()
设置,因此InnerClass
实例中的this$0
将包含与outerClassInstance
引用相同的值。
You can't use this field directly in code like 您不能在类似的代码中直接使用此字段
class Outer{
class Inner{
void test(){
System.out.println(this$0);//this will not compile
}
}
}
but you can access it via reflection. 但您可以通过反射访问它。 Code of method which will return value of this field could look like
将返回该字段值的方法代码可能类似于
public static Object getOuterInstance(Object inner)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
Class<?> clazz = inner.getClass();
Field f = clazz.getDeclaredField("this$0");
f.setAccessible(true);//in case of class placed in different package
return f.get(inner);
}
Example: 例:
class Outer {
private String name;
public Outer(String name) { this.name = name; }
public String getName() { return name; }
class Inner{}
}
class Demo {
public static void main(String[] args) throws Exception {
Outer o1 = new Outer("foo");
Outer o2 = new Outer("bar");
Inner i1 = o1.new Inner();
Inner i2 = o2.new Inner();
System.out.println(((Outer) getOuterInstance(i1)).getName());
System.out.println(((Outer) getOuterInstance(i2)).getName());
}
public static Object getOuterInstance(Object inner)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {
Class<?> clazz = inner.getClass();
Field f = clazz.getDeclaredField("this$0");
f.setAccessible(true);
return f.get(inner);
}
}
Output: 输出:
foo
bar
which means that we did in fact get correct instances. 这意味着我们确实得到了正确的实例。
In case of your example you will have to: 对于您的示例,您将必须:
ite
iterator ite
迭代器中的每个元素 Map
or if you need more precise type LinkedHashMap
. LinkedHashMap
为Map
或者如果需要更精确的类型LinkedHashMap
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.