[英]How to access variables from private static inner class
I've a class structure like this: 我有一个这样的类结构:
public class Outer{
private Outer.Inner personal;
public Outer(){
//processing.
//personal assigned value
}
........
private static class Inner {
private final Set<String> innerPersonal;
Inner(){
innerPersonal=new HashSet<>();
//populate innerPersonal
}
}
}
I get an object of Outer in my program, How can I extract innerPersonal in my program, using reflection. 我在程序中得到一个外部对象,如何使用反射在程序中提取innerPersonal 。
As you want to execute the code outside Outer
, you cannot use Outer.Inner.class
to refer to your static inner class
as it is private
, so here I propose an approach that will simply get first the value of the field personal
, then call getClass()
on the returned value of the field (assuming that it is not null
) to finally access to this inner class
which allows to access also to its field innerPersonal
. 当您要执行的外部代码Outer
,您不能使用Outer.Inner.class
参阅您的static inner class
,因为它是private
的,所以这里我提出一个办法,只会让该领域的第一个值personal
,然后调用最终返回此inner class
的字段的返回值(假定它不为null
getClass()
上的getClass()
,该inner class
也允许访问其内部字段innerPersonal
。
Outer outer = ...
// Get the declared (private) field personal from the public class Outer
Field personalField = Outer.class.getDeclaredField("personal");
// Make it accessible otherwise you won't be able to get the value as it is private
personalField.setAccessible(true);
// Get the value of the field in case of the instance outer
Object personal = personalField.get(outer);
// Get the declared (private) field innerPersonal from the private static class Inner
Field innerPersonalField = personal.getClass().getDeclaredField("innerPersonal");
// Make it accessible otherwise you won't be able to get the value as it is private
innerPersonalField.setAccessible(true);
// Get the value of the field in case of the instance personal
Set<String> innerPersonal = (Set<String>)innerPersonalField.get(personal);
@Retention(RetentionPolicy.RUNTIME)
public @interface Factory {
Class<?> value();
}
public class Outer{
private Outer.Inner personal;
public Outer(){
//processing.
//personal assigned value
}
@Factory(SomeType.class)
private static class Inner {
public final Set<String> innerPersonal;
Inner(){
innerPersonal=new HashSet<>();
//populate innerPersonal
}
}
}
Outer o = new Outer();
Object r = o.getClass().getAnnotationsByType(Factory.class);
maybe this works. 也许这可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.