如何从私有静态内部类访问变量

时间:2016-09-07 10:44:09

标签: java reflection

我有这样的课程结构:

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
        }
    }
}

我的程序中有一个Outer的对象, 如何使用反射在程序中提取 innerPersonal

2 个答案:

答案 0 :(得分:2)

由于您要在Outer之外执行代码,因此您无法使用Outer.Inner.class来引用static inner class,因为它是private,所以我在此提出一种方法将首先获取字段personal的值,然后在字段的返回值上调用getClass()(假设它不是null)以最终访问此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);

答案 1 :(得分:0)

@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);

也许这样可行。